沉浸式狀態列之Toolbar解決方案
阿新 • • 發佈:2019-02-16
1.style檔案中 去Title 狀態列透明
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
...
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus" >true</item>
</style>
2.通過padding撐出來狀態列
<android.support.v7.widget.Toolbar
android:id="@+id/toobar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
...
android:fitsSystemWindows="true"
android:paddingTop="@dimen/toolbar_padding_top"/>
3.在values, values-v19兩個資料夾內dimens.xml下分別宣告toolbar_padding_top變數,values資料夾下的值為0dp,而values-v19資料夾下的值為25dp.
<resources>
<dimen name="toolbar_padding_top">25dp</dimen>
</resources>
4.程式碼中設定
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 經測試在程式碼裡直接宣告透明狀態列更有效
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
initToolbar();
}
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.tb);
toolbar.setTitle("LynnRachel");
if (toolbar != null) {
setSupportActionBar(toolbar);
}
}
}