CoordinatorLayout status bar padding disappears from ViewPager 2nd page
Like sidecarcat, I ran into a similar issue (using v23.1.1). I post here a workaround by using the code of sidecarcat and add some code to remove superflous padding in some cases.
// in onCreateView: adjust toolbar padding
final int initialToolbarHeight = mToolbar.getLayoutParams().height;
final int initialStatusBarHeight = getStatusBarHeight();
mToolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int[] locToolbar = new int[2];
mToolbar.getLocationOnScreen(locToolbar);
int yToolbar = locToolbar[1];
int topPaddingToolbar = mToolbar.getPaddingTop();
if (isAdded()) {
//normal case : system status bar padding on toolbar : yToolbar = initialStatusBarHeight && topPaddingToolbar = 0
//abnormal case : no system status bar padding on toolbar -> toolbar behind status bar => add custom padding
if (yToolbar != initialStatusBarHeight && topPaddingToolbar == 0) {
mToolbar.setPadding(0, initialStatusBarHeight, 0, 0);
mToolbar.getLayoutParams().height = initialToolbarHeight + initialStatusBarHeight;
}
//abnormal case : system status bar padding and custom padding on toolbar -> toolbar with padding too large => remove custom padding
else if (yToolbar == initialStatusBarHeight && topPaddingToolbar == initialStatusBarHeight) {
mToolbar.setPadding(0, 0, 0, 0);
mToolbar.getLayoutParams().height = initialToolbarHeight;
}
}
}
});
return mRootView;
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
Solution proposed by Android Team in the answer of my reported defect. This code should finally work.
ViewPager mViewPager;
ViewCompat.setOnApplyWindowInsetsListener(mViewPager,
new OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v,
WindowInsetsCompat insets) {
insets = ViewCompat.onApplyWindowInsets(v, insets);
if (insets.isConsumed()) {
return insets;
}
boolean consumed = false;
for (int i = 0, count = mViewPager.getChildCount(); i < count; i++) {
ViewCompat.dispatchApplyWindowInsets(mViewPager.getChildAt(i), insets);
if (insets.isConsumed()) {
consumed = true;
}
}
return consumed ? insets.consumeSystemWindowInsets() : insets;
}
});