当滑动列表需要两侧阴影时,可以设置RecyclerView的FadingEdge属性:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fadingEdgeLength="50dp"
android:fadingEdge="horizontal"
android:requiresFadingEdge="horizontal" />
fadingEdgeLength参数为阴影的长度,当API Level>14 应该使用requiresFadingEdge
这样RecyclerView两端都会有阴影
如果仅需左侧或者是右侧需要 需要重写View类的获取阴影长度的方法
将不需要阴影的部分返回参数设置为0即可
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
class FadingEdgeRecyclerView : RecyclerView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun getLeftFadingEdgeStrength(): Float {
return 0F
}
override fun getRightFadingEdgeStrength(): Float {
return super.getRightFadingEdgeStrength()
}
override fun getTopFadingEdgeStrength(): Float {
return super.getTopFadingEdgeStrength()
}
override fun getBottomFadingEdgeStrength(): Float {
return super.getBottomFadingEdgeStrength()
}
}
当需要定制阴影时,原生方法不支持,只能使用替代方法
在外层包一个ImageView控件,通过监听RecyclerView的滑动来实现显示/隐藏阴影
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/ivLine"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@mipmap/icon_line"
android:visibility="gone" />
</FrameLayout>
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val isNotTop = recyclerView.canScrollHorizontally(-1)
ivLine.visibility = if (isNotTop) View.VISIBLE else View.GONE
}
})