<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);
}
}
});
网友评论