recyclerview点击item平移背景
时间: 2023-07-04 14:22:58 浏览: 130
要实现RecyclerView点击item平移背景的效果,可以通过自定义RecyclerView的ItemDecoration来实现。以下是实现的步骤:
1. 在res/drawable文件夹下创建一个selector文件,用来设置RecyclerView item的背景色变化。例如,创建一个名为background_item.xml的文件,代码如下:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimaryDark" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
</shape>
</item>
</selector>
```
这里定义了两个状态,一个是按下状态,一个是普通状态,分别设置了不同的背景颜色。
2. 在RecyclerView的Adapter中,设置ItemView的背景为上述selector文件,例如:
```kotlin
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
view.setBackgroundResource(R.drawable.background_item)
return ViewHolder(view)
}
```
3. 自定义一个ItemDecoration,并在其onDraw方法中实现item背景平移效果。例如:
```kotlin
class CustomItemDecoration : RecyclerView.ItemDecoration() {
private val mPaint = Paint()
private val mOffset = 20 // 偏移量
private val mTopLeftRectF = RectF()
private val mBottomRightRectF = RectF()
init {
mPaint.color = Color.WHITE
mPaint.isAntiAlias = true
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
// 计算矩形区域
val left = child.left - params.leftMargin - mOffset
val top = child.top - params.topMargin - mOffset
val right = child.right + params.rightMargin + mOffset
val bottom = child.bottom + params.bottomMargin + mOffset
mTopLeftRectF.set(left.toFloat(), top.toFloat(), child.left.toFloat(), child.top.toFloat())
mBottomRightRectF.set(child.right.toFloat(), child.bottom.toFloat(), right.toFloat(), bottom.toFloat())
// 绘制背景
c.drawRoundRect(mTopLeftRectF, 10f, 10f, mPaint)
c.drawRoundRect(mBottomRightRectF, 10f, 10f, mPaint)
}
}
}
```
这里设置了一个偏移量mOffset,用于控制背景平移的程度,可以根据实际需求进行调整。
4. 最后,将自定义的ItemDecoration设置给RecyclerView即可:
```kotlin
recyclerView.addItemDecoration(CustomItemDecoration())
```
这样,点击RecyclerView的item时就能实现背景平移效果了。
阅读全文