這里我使用了一個(gè)開源庫來設(shè)置statusbar的顏色,在app的build.gradle中添加
api 'com.jaeger.statusbarutil:library:1.5.1'
在onCreate中初始化statusbar的顏色為透明:
private void initStatusBar() {
// 設(shè)置status bar的顏色為透明,這個(gè)接口需要設(shè)置第3個(gè)參數(shù)(透明度)
StatusBarUtil.setColor(this, Color.TRANSPARENT, 0);
// 設(shè)置布局可以到status bar的區(qū)域
getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
接下來就是布局了,在布局中添加一個(gè)AppBarLayout凌节,并且它的子View是Toolbar
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|enterAlways">
<TextView
android:id="@+id/tv_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_gravity="center"
android:maxLines="1"
android:ellipsize="end"
android:layout_marginRight="8dp"
android:textColor="@android:color/white"
android:textSize="18sp" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.NestedScrollView>
這個(gè)Toolbar在AppBarLayout中就可以移動(dòng)了帖烘,添加
app:layout_scrollFlags="scroll|enterAlways"意思是跟隨下面的NestedScrollView的子View滾動(dòng)鸟辅,scroll表示上滑時(shí)跟著移動(dòng)出去,enterAlways表示一旦下滑猿推,就馬上進(jìn)入到屏幕片习,要實(shí)現(xiàn)跟著滾動(dòng),就要通過設(shè)置NestedScrollView的子View的屬性app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"讓它們有關(guān)聯(lián)蹬叭。