我們先看一下代碼:
public class MainActivity extends AppCompatActivity { ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21){ View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_main); ... }由于這個功能是Android5.0及以上的系統才支持的,因此我們先在代碼中做一個系統版本號的判斷,只有當版本號大于或等于21的時候,也就是5.0及以上系統時才會執行后面的代碼。
接著我們調用了getWindow().getDecorView()方法拿到當前活動的DecorView,再調用它的setSystemUiVisibility()方法來改變系統UI的顯示,這里傳入View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN和View.SYSTEM_UI_FLAG_LAYOUT_STABLE就表示活動的布局會顯示在狀態欄上面,最后調用一下setStatusBarColor()方法將狀態欄設置成透明色。
僅僅這些代碼就可以實現讓背景圖和狀態欄融合到一起的效果了。
不過,如果運行一下程序,你會發現還是有些問題,界面的頭布局幾乎和系統狀態欄緊貼到一起了,這是由于系統狀態欄已經成為我們布局的一部分,因此沒有單獨為它留空間。當然,這個問題也是非常好解決的,借助android:fitsSystemWindows屬性就可以了。
見代碼:
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimary"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:fitsSystemWindows="true"> </LinearLayout></FrameLayout>
這樣就可以了。
以上這篇Android 實現背景圖和狀態欄融合方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答