滑動顯示隱藏ToolBar

 <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>

在代碼中設(shè)置監(jiān)聽事件進(jìn)行滑動顯示隱藏

   mScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            int toolbarHeight = llTitle.getHeight();
            //當(dāng)滑動的距離 <= toolbar高度的時候,改變Toolbar背景色的透明度,達(dá)到漸變的效果
            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高度相等的情況,但是實際測試時發(fā)現(xiàn),標(biāo)題欄的背景色
                //很少能達(dá)到完全不透明的情況,所以這里又判斷了滑動距離大于toolbar高度的情況,
                //將標(biāo)題欄的顏色設(shè)置為完全不透明狀態(tài)
                llTitle.setBackgroundResource(R.color.colorPrimary);
                alphaToolbar.setVisibility(View.VISIBLE);
            }
        }
    });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容