我的布局中有这个:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primary"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:fitsSystemWindows="true">
...
</RelativeLayout>
但我的应用中没有paddingLeft
或paddingRight
。当我删除fitsSystemWindows
时,填充回来了。为什么?如何保留fitsSystemWindows
和填充?
答案 0 :(得分:4)
fitsSyatemWindows
属性覆盖填充应用了布局。
因此,要应用填充,您应为RelativeLayout
创建一个包装器布局,并为其添加fitsSystemWindows
属性,并将padding
添加到子RelativeLayout
。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primary"
android:fitsSystemWindows="true"> //this is container layout
<RelativeLayout
android:paddingLeft="32dp"
android:paddingRight="32dp"
..... > //now you can add padding to this
.....
</RelativeLayout>
</RelativeLayout>
答案 1 :(得分:4)
我只是在这里添加它,以防任何人在使用fitSystemWindows时需要删除顶部填充。使用自定义操作栏,DrawerLayout / NavigationView和/或片段时可能就是这种情况
public class CustomFrameLayout extends FrameLayout {
public CustomFrameLayout(Context context) {
super(context);
}
public CustomFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected boolean fitSystemWindows(Rect insets) {
// this is added so we can "consume" the padding which is added because
// `android:fitsSystemWindows="true"` was added to the XML tag of View.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN
&& Build.VERSION.SDK_INT < 20) {
insets.top = 0;
// remove height of NavBar so that it does add padding at bottom.
insets.bottom -= heightOfNavigationBar;
}
return super.fitSystemWindows(insets);
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
// executed by API >= 20.
// removes the empty padding at the bottom which equals that of the height of NavBar.
setPadding(0, 0, 0, insets.getSystemWindowInsetBottom() - heightOfNavigationBar);
return insets.consumeSystemWindowInsets();
}
}
我们必须扩展Layout类(在我的情况下为FrameLayout)并删除fitSystemWindows()
(对于API&lt; 20)或onApplyWindowInsets()
(对于API&gt; = 20)的顶部填充。