下面列出了怎么用android.view.WindowInsets的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Resources res = getResources();
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setOnApplyWindowInsetsListener(new OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
// Adjust page margins:
// A little extra horizontal spacing between pages looks a bit
// less crowded on a round display.
final boolean round = insets.isRound();
int rowMargin = res.getDimensionPixelOffset(R.dimen.page_row_margin);
int colMargin = res.getDimensionPixelOffset(round ?
R.dimen.page_column_margin_round : R.dimen.page_column_margin);
pager.setPageMargins(rowMargin, colMargin);
return insets;
}
});
pager.setAdapter(new SampleGridPagerAdapter(this, getFragmentManager()));
}
/**
* Find the safe area of DisplayCutout.
*
* @param activity {@link Activity} (Portrait and `windowLayoutInDisplayCutoutMode` != never)
* @return Safe cutout insets.
*/
public static Rect findCutoutSafeArea(@NonNull Activity activity) {
final Rect safeInsetRect = new Rect();
// TODO:Rewrite with android-x
// TODO:Consider alternatives
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return safeInsetRect;
}
// Fix: getDisplayCutout() on a null object reference (issue #110)
final WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
if (windowInsets == null) {
return safeInsetRect;
}
// set safeInsetRect
final DisplayCutout displayCutout = windowInsets.getDisplayCutout();
if (displayCutout != null) {
safeInsetRect.set(displayCutout.getSafeInsetLeft(), displayCutout.getSafeInsetTop(), displayCutout.getSafeInsetRight(), displayCutout.getSafeInsetBottom());
}
return safeInsetRect;
}
@Override
protected void onDraw(Canvas canvas) {
if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
WindowInsets insets = (WindowInsets) lastInsets;
if (!SharedConfig.smoothKeyboard) {
int bottomInset = insets.getSystemWindowInsetBottom();
if (bottomInset > 0) {
backgroundPaint.setColor(behindKeyboardColor);
canvas.drawRect(0, getMeasuredHeight() - bottomInset, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
}
}
if (hasCutout) {
backgroundPaint.setColor(0xff000000);
int left = insets.getSystemWindowInsetLeft();
if (left != 0) {
canvas.drawRect(0, 0, left, getMeasuredHeight(), backgroundPaint);
}
int right = insets.getSystemWindowInsetRight();
if (right != 0) {
canvas.drawRect(right, 0, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
}
}
}
}
/**
* Find the safe area of DisplayCutout.
*
* @param activity {@link Activity} (Portrait and `windowLayoutInDisplayCutoutMode` != never)
* @return Safe cutout insets.
*/
public static Rect findCutoutSafeArea(@NonNull Activity activity) {
final Rect safeInsetRect = new Rect();
// TODO:Rewrite with android-x
// TODO:Consider alternatives
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return safeInsetRect;
}
// Fix: getDisplayCutout() on a null object reference (issue #110)
final WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
if (windowInsets == null) {
return safeInsetRect;
}
// set safeInsetRect
final DisplayCutout displayCutout = windowInsets.getDisplayCutout();
if (displayCutout != null) {
safeInsetRect.set(displayCutout.getSafeInsetLeft(), displayCutout.getSafeInsetTop(), displayCutout.getSafeInsetRight(), displayCutout.getSafeInsetBottom());
}
return safeInsetRect;
}
@Override
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int paddingSize = insets.getSystemWindowInsetBottom();
int barSize = mNavigationView.getDefaultBarSize();
paddingSize = paddingSize == barSize ? 0 : paddingSize;
mContentLayout.setPaddingRelative(0, 0, 0, paddingSize);
RelativeLayout.LayoutParams layoutParams = (LayoutParams) mContentLayout.getLayoutParams();
if (paddingSize > 0 && !mNavigationView.isLandscape()) {
layoutParams.bottomMargin = -barSize;
} else {
layoutParams.bottomMargin = 0;
}
return super.onApplyWindowInsets(insets.replaceSystemWindowInsets(0, 0, 0, 0));
} else {
return insets;
}
}
/**
* 是否为允许全屏界面显示内容到刘海区域的刘海屏机型(与AndroidManifest中配置对应)
*/
public static boolean allowDisplayToCutout(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// 9.0系统全屏界面默认会保留黑边,不允许显示内容到刘海区域
Window window = activity.getWindow();
WindowInsets windowInsets = window.getDecorView().getRootWindowInsets();
if (windowInsets == null) {
return false;
}
DisplayCutout displayCutout = windowInsets.getDisplayCutout();
if (displayCutout == null) {
return false;
}
List<Rect> boundingRects = displayCutout.getBoundingRects();
return boundingRects.size() > 0;
} else {
return hasCutoutHuawei(activity)
|| hasCutoutOPPO(activity)
|| hasCutoutVIVO(activity)
|| hasCutoutXIAOMI(activity);
}
}
/**
* 把状态栏设成透明
*/
protected void setStatusBarTransparent() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
View decorView = getWindow().getDecorView();
decorView.setOnApplyWindowInsetsListener((v, insets) -> {
WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
return defaultInsets.replaceSystemWindowInsets(
defaultInsets.getSystemWindowInsetLeft(),
0,
defaultInsets.getSystemWindowInsetRight(),
defaultInsets.getSystemWindowInsetBottom());
});
ViewCompat.requestApplyInsets(decorView);
getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
}
}
@TargetApi(20)
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
if (insets != null) {
if (mApplyInsetsToShadow && mShadowView != null) {
MarginLayoutParams lp = (MarginLayoutParams)mShadowView.getLayoutParams();
if (lp.topMargin != insets.getSystemWindowInsetTop()) {
lp.topMargin = insets.getSystemWindowInsetTop();
}
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
getChildAt(i).dispatchApplyWindowInsets(insets);
}
}
return insets;
}
@Override public WindowInsets onApplyWindowInsets(final WindowInsets insets) {
if(insets.isRound()) {
heading.setGravity(Gravity.CENTER_HORIZONTAL);
// Adjust paddings for round devices
if(!hasAdjustedPadding) {
final int padding = heading.getPaddingTop();
heading.setPadding(padding, 2 * padding, padding, padding);
list.setPadding(padding, 0, padding, 0);
hasAdjustedPadding = true;
}
} else {
heading.setGravity(Gravity.START);
}
return super.onApplyWindowInsets(insets);
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
if (insets.isRound()) {
inset = -2;
setWatchFaceStyle(new WatchFaceStyle.Builder(EarthWatchFaceService.this)
.setHotwordIndicatorGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)
.setPeekOpacityMode(WatchFaceStyle.PEEK_OPACITY_MODE_TRANSLUCENT)
.setShowSystemUiTime(true)
.setShowUnreadCountIndicator(true)
.setStatusBarGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP)
.setViewProtectionMode(WatchFaceStyle.PROTECT_HOTWORD_INDICATOR
| WatchFaceStyle.PROTECT_STATUS_BAR)
.build());
} else {
inset = getResources().getDimensionPixelOffset(R.dimen.padding_square);
setWatchFaceStyle(new WatchFaceStyle.Builder(EarthWatchFaceService.this)
.setHotwordIndicatorGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)
.setPeekOpacityMode(WatchFaceStyle.PEEK_OPACITY_MODE_TRANSLUCENT)
.setShowSystemUiTime(true)
.setShowUnreadCountIndicator(true)
.setStatusBarGravity(Gravity.END | Gravity.TOP)
.setViewProtectionMode(WatchFaceStyle.PROTECT_HOTWORD_INDICATOR
| WatchFaceStyle.PROTECT_STATUS_BAR)
.build());
}
}
public static void isNavigationBarExist(Activity activity) {
if (activity == null) {
return;
}
final int height = getNavigationHeight(activity);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
activity.getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets windowInsets) {
boolean isShowing = false;
int b = 0;
if (windowInsets != null) {
b = windowInsets.getSystemWindowInsetBottom();
isShowing = (b == height);
}
print("导航栏到底存不存存在----" + isShowing);
// if (onNavigationStateListener != null && b <= height) {
// onNavigationStateListener.onNavigationState(isShowing, b);
// }
return windowInsets;
}
});
}
}
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
WindowInsets copy = new WindowInsets(insets);
ViewGroup viewGroup = (ViewGroup) v;
final int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
viewGroup.getChildAt(i).dispatchApplyWindowInsets(copy);
}
return insets.consumeSystemWindowInsets();
}
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
int top = insets.getSystemWindowInsetTop();
if (mContentView.getLayoutParams() instanceof MarginLayoutParams) {
MarginLayoutParams params = (MarginLayoutParams) mContentView.getLayoutParams();
mInsets.set(params.leftMargin, params.topMargin + top, params.rightMargin, params.bottomMargin);
}
applyWindowInset();
return super.onApplyWindowInsets(insets);
}
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (insets == null) {
return null;
} else {
setInsets(new Rect(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()));
}
return insets;
}
public static void applyMarginInsets(ViewGroup.MarginLayoutParams lp, Object insets,
int gravity) {
WindowInsets wi = (WindowInsets) insets;
if (gravity == Gravity.LEFT) {
wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
} else if (gravity == Gravity.RIGHT) {
wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
}
lp.leftMargin = wi.getSystemWindowInsetLeft();
lp.topMargin = wi.getSystemWindowInsetTop();
lp.rightMargin = wi.getSystemWindowInsetRight();
lp.bottomMargin = wi.getSystemWindowInsetBottom();
}
@Override public WindowInsets onApplyWindowInsets(WindowInsets insets) {
ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = insets.getSystemWindowInsetTop();
listener.onResize();
return insets.consumeSystemWindowInsets();
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (newAPI)
((AndroidDrawableMetrics) Native.graphics().metrics()).updateInsets(insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(),
insets.getSystemWindowInsetBottom(),
insets.getSystemWindowInsetLeft());
return super.onApplyWindowInsets(insets); //To change body of generated methods, choose Tools | Templates.
}
@SuppressLint("NewApi")
private void dispatchChildInsets(View child, Object insets, int drawerGravity)
{
WindowInsets wi = (WindowInsets) insets;
if (drawerGravity == Gravity.LEFT)
{
wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(), wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
}
else if (drawerGravity == Gravity.RIGHT)
{
wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(), wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
}
child.dispatchApplyWindowInsets(wi);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Resources res = getResources();
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setOnApplyWindowInsetsListener(new OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
// Adjust page margins:
// A little extra horizontal spacing between pages looks a bit
// less crowded on a round display.
final boolean round = insets.isRound();
int rowMargin = res.getDimensionPixelOffset(R.dimen.page_row_margin);
int colMargin = res.getDimensionPixelOffset(round ?
R.dimen.page_column_margin_round : R.dimen.page_column_margin);
pager.setPageMargins(rowMargin, colMargin);
// GridViewPager relies on insets to properly handle
// layout for round displays. They must be explicitly
// applied since this listener has taken them over.
pager.onApplyWindowInsets(insets);
return insets;
}
});
pager.setAdapter(new SampleGridPagerAdapter(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
private int getTopInset(Object insets)
{
if (Build.VERSION.SDK_INT >= 21)
{
return insets != null ? ((WindowInsets) insets).getSystemWindowInsetTop() : 0;
}
return 0;
}
@Override
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
mBottomSheetView.setPadding(
mBottomSheetView.getPaddingLeft(),
mBottomSheetView.getPaddingTop(),
mBottomSheetView.getPaddingRight(),
(int) (insets.getSystemWindowInsetBottom() + mConfig.getExtraPaddingBottom())
);
return insets;
}
public static void applyMarginInsets(ViewGroup.MarginLayoutParams lp, Object insets,
int gravity) {
WindowInsets wi = (WindowInsets) insets;
if (gravity == Gravity.LEFT) {
wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(),
wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
} else if (gravity == Gravity.RIGHT) {
wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(),
wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
}
lp.leftMargin = wi.getSystemWindowInsetLeft();
lp.topMargin = wi.getSystemWindowInsetTop();
lp.rightMargin = wi.getSystemWindowInsetRight();
lp.bottomMargin = wi.getSystemWindowInsetBottom();
}
/**
* A menu button is drawn at the top of the screen if a menu is not currently visible. This button
* offers the user the possibility of clearing the focus or choosing global actions (i.e Home,
* Back, Notifications, etc). This menu button should be displayed if the user is using group
* selection or point scanning.
*/
public void drawMenuButtonIfMenuNotVisible() {
if (!isMenuVisible()) {
Button menuButton = (Button) globalMenuButtonOverlay.findViewById(R.id.global_menu_button);
if (!menuButton.hasOnClickListeners()) {
menuButton.setOnClickListener(view -> drawGlobalMenu());
}
// Adjust the global menu button after it's drawn to ensure it's not obscured by a notch. Only
// do so if the button is not already visible to avoid re-drawing the button every time
// the screen changes or every time the highlight moves.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && !globalMenuButtonOverlay.isVisible()) {
// When switching from having a cutout to having no cutout (e.g. turning a notched phone
// sideways to landscape mode), we change the gravity to CENTER_HORIZONTAL in
// #adjustGlobalMenuButtonPosition.
globalMenuButtonOverlay
.getRootView()
.post(
() -> {
WindowInsets windowInsets =
this.globalMenuButtonOverlay.getRootView().getRootWindowInsets();
// Because of how View.getLayoutOnScreen renders in Q, we need to first check
// that there is an inset before adjusting the gravity. Otherwise, the highlight
// can be incorrect on screens without a display cutout.
if (windowInsets == null) {
return;
}
DisplayCutout displayCutout = windowInsets.getDisplayCutout();
if (displayCutout == null) {
adjustGlobalMenuButtonPosition(displayCutout, new ArrayList<>());
} else {
adjustGlobalMenuButtonForDisplayCutouts();
}
});
}
showGlobalMenu();
}
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
mInsets[0] = insets.getSystemWindowInsetLeft();
mInsets[1] = insets.getSystemWindowInsetTop();
mInsets[2] = insets.getSystemWindowInsetRight();
return super.onApplyWindowInsets(insets.replaceSystemWindowInsets(0, 0, 0, insets.getSystemWindowInsetBottom()));
}
else {
return super.onApplyWindowInsets(insets);
}
}
public static void setStatusBarTranslucent(Window window, boolean translucent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setRenderContentInShortEdgeCutoutAreas(window, translucent);
View decorView = window.getDecorView();
if (translucent) {
decorView.setOnApplyWindowInsetsListener((v, insets) -> {
WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
return defaultInsets.replaceSystemWindowInsets(
defaultInsets.getSystemWindowInsetLeft(),
0,
defaultInsets.getSystemWindowInsetRight(),
defaultInsets.getSystemWindowInsetBottom());
});
} else {
decorView.setOnApplyWindowInsetsListener(null);
}
ViewCompat.requestApplyInsets(decorView);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (translucent) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
ViewCompat.requestApplyInsets(window.getDecorView());
}
}
@TargetApi(28)
private static boolean attachHasOfficialNotch(View view) {
WindowInsets windowInsets = view.getRootWindowInsets();
if (windowInsets != null) {
DisplayCutout displayCutout = windowInsets.getDisplayCutout();
return displayCutout != null;
} else {
throw new IllegalStateException("activity has not yet attach to window, you must call `isCutout` after `Activity#onAttachedToWindow` is called.");
}
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();
lp.topMargin = insets.getSystemWindowInsetTop();
setLayoutParams(lp);
}
return super.onApplyWindowInsets(insets);
}
@SuppressLint("NewApi")
private void dispatchChildInsets(View child, Object insets, int drawerGravity)
{
WindowInsets wi = (WindowInsets) insets;
if (drawerGravity == Gravity.LEFT)
{
wi = wi.replaceSystemWindowInsets(wi.getSystemWindowInsetLeft(), wi.getSystemWindowInsetTop(), 0, wi.getSystemWindowInsetBottom());
}
else if (drawerGravity == Gravity.RIGHT)
{
wi = wi.replaceSystemWindowInsets(0, wi.getSystemWindowInsetTop(), wi.getSystemWindowInsetRight(), wi.getSystemWindowInsetBottom());
}
child.dispatchApplyWindowInsets(wi);
}
private int getTopInset(Object insets)
{
if (Build.VERSION.SDK_INT >= 21)
{
return insets != null ? ((WindowInsets) insets).getSystemWindowInsetTop() : 0;
}
return 0;
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
mYOffset = getResources().getDimension( R.dimen.y_offset );
if( insets.isRound() ) {
mXOffset = getResources().getDimension( R.dimen.x_offset_round );
} else {
mXOffset = getResources().getDimension( R.dimen.x_offset_square );
}
}