在Android開發中,我們有時候需要讓布局充滿整個屏幕,或者需要控制布局和系統UI的交互關係。此時,Android提供了一個非常有用的屬性,就是fitssystemwindows。它可以控制布局與系統UI之間的交互,保證應用程序UI不會被系統UI擋住或者覆蓋,同時也能讓UI更加美觀。
一、什麼是fitssystemwindows
fitssystemwindows是Android提供的一個屬性,設置該屬性為true時,可以使ViewGroup擴展到屏幕的邊緣 ,並且會留出系統UI的空間。系統UI包括狀態欄、導航欄、輸入法等,系統UI是指Android系統上方的一部分屏幕區域。
例如設置Activity的布局文件中設置:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true"> ... </LinearLayout>
設置fitssystemwindows=true屬性後,LinearLayout就會頂部與狀態欄平齊,並且底部會留出導航欄的位置.
二、fitssystemwindows適用場景
1.全屏應用
對於需要全屏顯示的應用程序,為了避免系統UI覆蓋應用UI,可以設置root view的fitsSystemWindows屬性為true,從而讓布局能夠正常顯示並且能夠避免UI部分被覆蓋。
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> ... </androidx.constraintlayout.widget.ConstraintLayout>
2.使用Toolbar
當我們在界面中使用Toolbar時,為了避免狀態欄和Toolbar重疊,我們可以使用fitsSystemWindows屬性來為Toolbar留出狀態欄的位置。
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:fitsSystemWindows="true">
3.滑動控件
當我們使用一些滑動控件(例如RecyclerView、ScrollView等)時,如果不設置fitsSystemWindows屬性,控件的起始位置會被遮擋住一部分,會讓用戶體驗感受較差。
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> ... </ScrollView>
三、適配各種平台版本
由於系統UI在不同的Android版本中有所不同,所以適配各種版本的系統UI也是非常重要的一點。我們可以通過代碼檢測狀態欄和導航欄的高度,然後通過設置fitsSystemWindows屬性實現合適的適配。
例如,在Activity的onCreate()方法中,我們可以使用以下代碼判斷系統UI的高度,然後設置fitsSystemWindows屬性。
// 設置fitsSystemWindows屬性為true ViewGroup rootView = findViewById(android.R.id.content); ViewCompat.setOnApplyWindowInsetsListener(rootView, new OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) { // 獲取狀態欄高度和導航欄高度 int statusBarHeight = insets.getSystemWindowInsetTop(); int navigationBarHeight = insets.getSystemWindowInsetBottom(); // 設置fitsSystemWindows屬性為true v.setPadding(0, statusBarHeight, 0, navigationBarHeight); return insets; } });
四、結論
通過本文的介紹,我們了解了Android fitssystemwindows屬性的作用和使用方法,同時也介紹了fitssystemwindows的適用場景和在各種平台版本中的適配方法。
原創文章,作者:WYRUO,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/349374.html