![](/img/trans.png)
[英]How to handle Horizontal RecyclerView inside Vertical RecyclerView
[英]How to handle onTouchListener inside a RecyclerView
我需要一些幫助來解決我的問題。 我有一個 recyclerview,它的項目包含一個 ImageView。我想用手指移動 imageview。 我創建了一個 touchListener 並將其設置在 imageview 的適配器中。
下圖顯示了我的物品的外觀。 我想向左或向右移動黑色方塊,當它碰到綠色/藍色布局的邊緣時,它就會回到中心。
我分享我的適配器代碼,我的聽眾。
適配器:
class RecyclerViewAdapter( private val items: List<String>) :
RecyclerView.Adapter<RecyclerViewAdapter.Holder>() {
inner class Holder(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val binding = ItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return Holder(binding)
}
@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.binding.image.setOnTouchListener(
MyTouchInterface(
image = holder.binding.image,
container = holder.binding.container
)
)
}
override fun getItemCount() = items.size
}
觸摸監聽器:
class MyTouchInterface(
private val image: AppCompatImageView,
private val container: View
) : View.OnTouchListener {
private var downPT = PointF()
private var startPT = PointF()
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(view: View?, event: MotionEvent?): Boolean {
val defaultPosition =
container.x + (container.width / 2 - image.width / 2)
when (event!!.action) {
MotionEvent.ACTION_MOVE -> {
image.x = (startPT.x + event.x - downPT.x)
startPT[image.x] = image.y
container.doOnLayout {
if ((startPT.x + event.x) - downPT.x < (defaultPosition - image.width)) {
Log.e("POS left", "${(startPT.x + event.x) - downPT.x}")
}
if ((startPT.x + event.x) - downPT.x > (defaultPosition + image.width)) {
Log.e("POS right", "${(startPT.x + event.x) - downPT.x}")
}
}
}
MotionEvent.ACTION_DOWN -> {
downPT[event.x] = event.y
startPT[image.x] = image.y
}
MotionEvent.ACTION_UP -> {
image.x = defaultPosition
}
else -> {}
}
return true
}
}
問題是圖像沒有移動或只是一點點但永遠不會回到中心。 我讀過它,我發現這是因為 recyclerview。
感謝您的幫助!
您必須在觸摸時處理 recyclerView 的 suppressLayout。
1 - 創建接口
interface AdapterTouchListener {
fun onTouched()
fun onReleased()
}
2 - 您的適配器 class
class MyAdapter(
private val touchListener: AdapterTouchListener
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
// TODO: rest of the adapter code
override fun onBindViewHolder(holder: PlayBackKeyAdapter.MyViewHolder, position: Int) {
holder.binding.imageKey.setOnTouchListener { _, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
touchListener.onTouched()
}
MotionEvent.ACTION_UP -> {
touchListener.onReleased()
}
}
true
}
}
}
3 - 在您的活動/片段中初始化適配器並使用 suppressLayout
val myAdapter = MyAdapter(object
:PlayBackKeyAdapter.AdapterTouchListener{
override fun onTouched() {
binding.recyclerView.suppressLayout(true)
}
override fun onReleased() {
binding.recyclerView.suppressLayout(false)
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.