自定義CoordinatorLayout的Behavior,實現ToolBar透明漸變效果
阿新 • • 發佈:2019-01-26
1.佈局
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/header" android:layout_width="match_parent" android:layout_height="@dimen/header_height" //圖片高度為200dp android:scaleType="centerCrop" android:src="@mipmap/header_img"/> <TextView style="@style/TextAppearance.AppCompat.Display2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Android支付寶支付整合\nAndroid支付寶支付整合Android支付寶\n支付整合Android支付寶支付整合"/> </LinearLayout> </android.support.v4.widget.NestedScrollView> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_behavior" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_behavior="liuwp.com.attendance.activity.ToolbarAlphaBehavior" /> </android.support.design.widget.CoordinatorLayout>
2.實現自定義的ToolbarAlphaBehavior
public class ToolbarAlphaBehavior extends CoordinatorLayout.Behavior<Toolbar> { private static final String TAG = "ToolbarAlphaBehavior"; private int offset = 0; private int startOffset = 0; private int endOffset = 0; private Context context; public ToolbarAlphaBehavior(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, Toolbar child, View directTargetChild, View target, int nestedScrollAxes) { return true; } @Override public void onNestedScroll(CoordinatorLayout coordinatorLayout, Toolbar toolbar, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { startOffset = 0; endOffset = context.getResources().getDimensionPixelOffset(R.dimen.header_height) - toolbar.getHeight(); offset += dyConsumed; if (offset <= startOffset) { //alpha為0 toolbar.getBackground().setAlpha(0); } else if (offset > startOffset && offset < endOffset) { //alpha為0到255 float precent = (float) (offset - startOffset) / endOffset; int alpha = Math.round(precent * 255); toolbar.getBackground().setAlpha(alpha); } else if (offset >= endOffset) { //alpha為255 toolbar.getBackground().setAlpha(255); } } }
3. 給Toolbar配置behavior
app:layout_behavior="com.xxx.activity.ToolbarAlphaBehavior" //新增配置
4.toolbar的透明初始化 在oncreate方法中
toolbar.getBackground().setAlpha(0);//toolbar透明度初始化為0