沉浸式能够使状态栏和导航栏同App背景颜色融为一体,不再是两头黑色的丑陋外观,可以大大提升其用户体验,但是在沉浸式的实现中会出现一些难点,本文就来总结一下几种好用的实现方法。
沉浸式实现原理其实是使整个activity布局延伸到整个屏幕,同时将状态栏(上方)和导航栏(下方)变为透明色,就能够初步实现我们想要的效果。
public class BaseActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ImmersionBar.with(this).init();
}
@Override
protected void onDestroy(){
super.onDestroy();
ImmersionBar.with(this).destroy();
}
}
但是这样会出现的问题是,app顶部组件紧靠屏幕上方,导致状态栏和顶部重合,使界面仍然不够美观,主要的解决方式有如下三种:
1、在toolbar上方添加<View/>,高度设置为"0dp",即可实现,代码如下
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@color/colorPrimary" />
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:title="教务系统app"
app:titleTextColor="@android:color/white" />
2、使用fitsSystemWindows,在布局文件的根节点使用android:fitsSystemWindows="true"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
</LinearLayout>
然后使用ImmersionBar时候必须指定状态栏颜色
ImmersionBar.with(this)
.statusBarColor(R.color.colorPrimary)
.init();
3、使用ImmersionBar的fitsSystemWindows(boolean fits)方法
获得rootView的根节点,然后设置距离顶部的padding值为状态栏的高度值
ImmersionBar.with(this)
.statusBarColor(R.colorPrimary)
.fitsSystemWindows(true)
.init();
以上做法只是为了适配Android4.4以前的版本,如果不考虑这个问题的话,只需要如下的三行代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏,将以下两行代码加入onCreate()方法中,
//要注意,在setContentView()之后
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// Set up the activity_login form.
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
Button loginBtn = (Button) findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//login();
new Thread(new Runnable() {
@Override
public void run() {
try {
attemptLogin();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
googleClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
另外,在Activity对应的xml文件根元素中,加入
<RelativeLayout
...
android:fitsSystemWindows="true"
android:clipToPadding="true"
...
>
重新编译运行即可发现,状态栏和导航栏变为沉浸式,背景与xml根节点背景融为一体
但是,当系统自动调出虚拟键盘的时候,导航栏颜色仍然没有改变,这也是这种实现方法的一个问题,目前仍在思考如何解决
网友评论