2015-10-15 3 views
5

у меня есть это в моем макете:fitsSystemWindows удаляет обивка

<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

Это было рассмотрено в статье - [Почему я хочу подгонятьSystemWindows?] (Https://medium.com/google-developers/why-would-i-want-to-fitssystemwindows-4e26d9ce1eec#.kpokdt33j). – Sufian

ответ

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> 
+3

Не то, чтобы он игнорировал дополнение как таковое, это то, что fitsSystemWindows ** переопределяет ** заполнение с достаточным количеством отступов, чтобы сделать вид системных окон. – ianhanniballake

+0

@ianhanniballake aw! Спасибо за исправление моей ошибки :) Улучшение ответа – Apurva

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 < 20) или onApplyWindowInsets() (для API> = 20).

Смежные вопросы