@TryLoveCatch
2022-11-02T09:20:41.000000Z
字数 2855
阅读 435
Android知识体系
RecyclerView
RecyclerView在往上滑动的时候,期望Item有一个渐变的效果
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/home_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/home_recycle_margin"
android:layout_marginLeft="@dimen/home_recycle_margin"
android:layout_marginRight="@dimen/home_recycle_margin"
android:scrollbars="none"
android:overScrollMode="never"
android:fadingEdgeLength="@dimen/home_recycle_fading_edge_height"
android:requiresFadingEdge="vertical"
/>
主要是fadingEdgeLength 和 requiresFadingEdge两个属性
<FrameLayout
android:id="@+id/home_recycler_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/home_recycle_margin"
android:layout_marginLeft="@dimen/home_recycle_margin"
android:layout_marginRight="@dimen/home_recycle_margin"
android:visibility="gone">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/home_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:overScrollMode="never"
/>
<ImageView
android:id="@+id/home_img_edge"
android:layout_width="match_parent"
android:layout_height="32dp"
android:background="#ff0000"
android:visibility="gone" />
</FrameLayout>
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
boolean isNotTop = recyclerView.canScrollVertically(-1);
mImgEdge.setVisibility(isNotTop ? View.VISIBLE : View.GONE);
}
});
增加一个ImageView放在RecyclerView的顶部,然后在onScrollStateChanged的时候控制ImageView的显示和隐藏。
在第一次更新RecycleView的时候,onScrollStateChanged并没有执行,导致ImageView没有显示出来,后续滑动才会显示出来
参考:https://blog.csdn.net/linyukun6422/article/details/52516022
使用ItemDecoration来实现
private class MyItemDecoration extends RecyclerView.ItemDecoration {
private Paint mPaint;
private int mHeight;
private int mColorStart;
private int mColorEnd;
public MyItemDecoration() {
mPaint = new Paint();
mHeight = getResources().getDimensionPixelSize(R.dimen.home_recycle_fading_edge_height);
mColorStart = ContextCompat.getColor(getContext(), R.color.home_recycle_fading_edge_start_color);
mColorEnd = ContextCompat.getColor(getContext(), R.color.home_recycle_fading_edge_end_color);
}
@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDrawOver(c, parent, state);
boolean isNotTop = parent.canScrollVertically(-1);
if (isNotTop) {
LinearGradient gradient = new LinearGradient(0, 0, 0, mHeight,
new int[] {mColorStart, mColorEnd},
new float[]{0f, 1.0f},
Shader.TileMode.CLAMP);
mPaint.setShader(gradient);
c.drawRect(0, 0, parent.getWidth(), mHeight, mPaint);
}
}
}
自定义控件三部曲视图篇(五)——RecyclerView系列之二ItemDecoration
ItemDecoration介绍以及应用