Android之沉浸式狀態欄

 

大神寫的兩個ToolBar的庫

StatusBarUtil

ImmersionBar

這個特性是andorid4.4支持的,最少要api19纔可以使用,低於4.4以下是不能修改的。下面介紹一下使用的方法,非常得簡單:

public class MainActivity extends Activity {

    private ListView listview;

    private MyAdapter adapter;
    private static String[] list = new String[]{"全國省市區", "時間"};
    private static Class[] classes = new Class[]{ProvincialCityActivity.class, TimeActivity.class};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //沉浸頂部狀態欄
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //沉浸底部虛擬鍵
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        listview = (ListView) findViewById(R.id.listview);
        adapter = new MyAdapter();
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(MainActivity.this, classes[i]));
            }
        });

    }

看佈局:activity_main 佈局


 
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:gravity="center_horizontal"  android:orientation="vertical"> <ListView  android:id="@+id/listview"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:background="#009959" /> </LinearLayout> 

看圖片


 
 

 

大家看到了吧,文字和狀態欄重疊在一起了,這肯定是不行的,此時需要添加下面的代碼:

 


 
android:clipToPadding="true" android:fitsSystemWindows="true" 

activity_main 佈局中添加

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#009959"
        android:clipToPadding="true"
        android:fitsSystemWindows="true" />

</LinearLayout>

加入那兩行以後,界面仍然會是沉浸式的,但狀態欄那部分,就不會再重疊了,像加了padding一樣,如下圖:



 

相關函數:


 
  1. fitsSystemWindows, 該屬性可以設置是否爲系統 View 預留出空間, 當設置爲 true 時,會預留出狀態欄的空間。

  2. ContentView, 實質爲 ContentFrameLayout, 但是重寫了 dispatchFitSystemWindows 方法, 所以對其設置 fitsSystemWindows 無效。

  3. ContentParent, 實質爲 FitWindowsLinearLayout, 裏面第一個 View 是 ViewStubCompat, 如果主題沒有設置 title ,它就不會 inflate .第二個 View 就是 ContentView。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章