<android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:sct="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
……/>
<LinearLayout
android:id="@+id/llTitle"
android:layout_width="match_parent"
android:layout_height="@dimen/dm_75"
android:background="@android:color/transparent"
android:orientation="vertical"
android:paddingTop="@dimen/dm_25">
<android.support.v7.widget.Toolbar
android:id="@+id/alphaToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:visibility="gone"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:titleTextColor="@color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:singleLine="true"
android:text="@string/home_title"
android:textColor="@color/white"
android:textSize="18dp" />
</android.support.v7.widget.Toolbar>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
在代碼中設置監聽事件進行滑動顯示隱藏
mScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
int toolbarHeight = llTitle.getHeight();
//當滑動的距離 <= toolbar高度的時候,改變Toolbar背景色的透明度,達到漸變的效果
if (mScroll.getScrollY() <= toolbarHeight) {
float scale = (float) mScroll.getScrollY() / toolbarHeight;
float alpha = scale * 255;
llTitle.setBackgroundColor(Color.argb((int) alpha, 128, 0, 0));
alphaToolbar.setVisibility(View.GONE);
} else {
//上述雖然判斷了滑動距離與toolbar高度相等的情況,但是實際測試時發現,標題欄的背景色
//很少能達到完全不透明的情況,所以這里又判斷了滑動距離大于toolbar高度的情況,
//將標題欄的顏色設置為完全不透明狀態
llTitle.setBackgroundResource(R.color.colorPrimary);
alphaToolbar.setVisibility(View.VISIBLE);
}
}
});