基于android的沉浸式app设计,直接植入项目即可完成
//设置状态栏的透明属性
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0 全透明实现
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
}
但是有一种情况会导致设计失效,在ScrollView中嵌套EditText会导致状态栏拉伸,十分影响体验,这时候就需要手动设置状态栏高度来解决,通过反射来获取状态栏高度,从而进一步设置ToolBar
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
/**
* <!-- Height of the status bar -->
* <dimen name="status_bar_height">24dp</dimen>
* <!-- Height of the bottom navigation / system bar. -->
* <dimen name="navigation_bar_height">48dp</dimen>
* 反射手机运行的类:android.R.dimen.status_bar_height.
*/
private int getStatusBarHeight(Context context) {
int statusHeight = -1;
try {
@SuppressLint("PrivateApi") Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
String status_bar_height = clazz.getField("status_bar_height").get(object).toString();
int height = Integer.parseInt(status_bar_height);
//dp -> px
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
toolbar = findViewById(R.id.toolBar);
LayoutParams layoutParams = toolbar.getLayoutParams();
layoutParams.height += getStatusBarHeight(this);
toolbar.setLayoutParams(layoutParams);
toolbar.setPadding(
toolbar.getPaddingLeft(),
toolbar.getPaddingTop()+getStatusBarHeight(this),
toolbar.getPaddingRight(),
toolbar.getPaddingBottom());
网友评论