gpt4 book ai didi

android - 如何在 androidx.recyclerview.widget 中使用 androidx.recyclerview.selection。或者如何在 android 中使用 kotlin 在 recyclerview 中选择一个项目?

转载 作者:行者123 更新时间:2023-11-29 22:55:33 30 4
gpt4 key购买 nike

我创建了一个水平回收器 View ,其中加载了项目。之后,我需要选择该项目并执行点击事件。到这个存档(代码在下面可用),现在我想改变点击项目的颜色,剩下的项目应该被取消选择。如果我没有正确查询,请道歉。

这一切都是使用 Kotlin 的 Androidx Recyclerview 构建的。这是 sample code !我正在寻找一个解决方案来扩展它以选择项目并更改其颜色。

使用 kotlin 编码的 Android Activity



import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_sample.*
import androidx.recyclerview.widget.RecyclerView



class SampleActivity : AppCompatActivity() {

val bottle_name: ArrayList<String> = ArrayList()
val bottle_img: ArrayList<Int> = ArrayList()
val bottle_type: ArrayList<String> = ArrayList()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)

addBottles()


val adptr = BottlesAdaptor(bottle_name, bottle_img, bottle_type);
bottles_list.adapter = adptr

val layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
val recyclerView = bottles_list
recyclerView.setLayoutManager(layoutManager)

}

override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
hideSystemUI()
}
}

private fun hideSystemUI() {
val decorView = window.decorView
decorView.systemUiVisibility = (
View.SYSTEM_UI_FLAG_IMMERSIVE
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}

fun addBottles(){
bottle_name.add("Coca1");
bottle_name.add("Coca2");
bottle_name.add("Coca3");
bottle_name.add("Coca4");
bottle_name.add("Coca5");
bottle_name.add("Coca6");
bottle_name.add("Coca7");
bottle_name.add("Coca8");
bottle_type.add("cooldrink");
bottle_type.add("cooldrink");
bottle_type.add("cooldrink");
bottle_type.add("cooldrink");
bottle_type.add("cooldrink");
bottle_type.add("wine");
bottle_type.add("wine");
bottle_type.add("wine");
bottle_img.add(R.drawable.coca1);
bottle_img.add(R.drawable.coca2);
bottle_img.add(R.drawable.coca3);
bottle_img.add(R.drawable.coca4);
bottle_img.add(R.drawable.coca5);
bottle_img.add(R.drawable.coca6);
bottle_img.add(R.drawable.coca7);
bottle_img.add(R.drawable.coca8);


}

使用 Kotlin 编码的 Bottles 适配器


import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.bottle_list_item.view.*
import androidx.recyclerview.widget.RecyclerView


class BottlesAdaptor(private val dataSet: ArrayList<String>, private val dataSet2: ArrayList<Int>, private val dataSet3: ArrayList<String>) :
RecyclerView.Adapter<BottlesAdaptor.ViewHolder>() {

/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val textView: TextView
val imageView: ImageView
val textView2:TextView

init {
// Define click listener for the ViewHolder's View.
v.setOnClickListener {
Log.d(TAG, "Element $adapterPosition clicked.")
// I have tried this but it is not giving me the opportunity to select a color for the selected item
if (v.id==adapterPosition){
v.setBackgroundResource(R.drawable.bottle_card_selected);
}
else{
v.setBackgroundResource(R.drawable.bottle_card);
}
}
textView = v.findViewById(R.id.bottle_list_text)
imageView = v.findViewById(R.id.bottle_list_img)
textView2 = v.findViewById(R.id.bottle_list_subtext)
}
}

// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
// Create a new view.
val v = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.bottle_list_item, viewGroup, false)

return ViewHolder(v)
}

// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
Log.d(TAG, "Element $position set.")

// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.textView.text = dataSet[position]
viewHolder.textView2.text = dataSet3[position]
viewHolder.imageView.setImageResource(dataSet2[position])
}

// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount() = dataSet.size


companion object {
private val TAG = "CustomAdapter"
}
}


我期待一种更好的解决方案。如果可能的话,还希望禁用特定按钮。它应该给recyclerview的可选项目的选项

最佳答案

首先,将以下内容添加到您的 build.gradle(应用级):

implementation "androidx.recyclerview:recyclerview-selection:1.0.0

在 RecyclerView Adapter BottlesAdaptor 中设置选择跟踪器:

private var tracker: SelectionTracker<Long>? = null

fun setTracker(tracker: SelectionTracker<Long>?) {
this.tracker = tracker
}

在您的 Activity SampleActivity 中使用以下方法来实现选择跟踪器:

private fun trackSelectedItems() {
tracker = SelectionTracker.Builder<Long>(
"selection-1",
bottles_list,
ItemIdKeyProvider(bottles_list),
ItemLookup(bottles_list),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.createSelectAnything())
.build()

adptr?.setTracker(tracker)

tracker?.addObserver(object: SelectionTracker.SelectionObserver<Long>() {
override fun onSelectionChanged() {
//handle the selected according to your logic
}
})
}

像这样添加 ItemIdKeyProvider():

inner class ItemIdKeyProvider(private val recyclerView: RecyclerView)
: ItemKeyProvider<Long>(SCOPE_MAPPED) {

override fun getKey(position: Int): Long? {
return recyclerView.adapter?.getItemId(position)
?: throw IllegalStateException("RecyclerView adapter is not set!")
}

override fun getPosition(key: Long): Int {
val viewHolder = recyclerView.findViewHolderForItemId(key)
return viewHolder?.layoutPosition ?: RecyclerView.NO_POSITION
}
}

添加 ItemLookup,如下所示:

inner class ItemLookup(private val rv: RecyclerView)
: ItemDetailsLookup<Long>() {
override fun getItemDetails(event: MotionEvent)
: ItemDetails<Long>? {

val view = rv.findChildViewUnder(event.x, event.y)
if(view != null) {
return (rv.getChildViewHolder(view) as BottlesAdaptor.ViewHolder)
.getItemDetails()
}
return null
}
}

由于您还提到 现在我想更改被点击项目的颜色并且应该取消选择剩余项目,因此在您的 Adapter 的onBindViewHolder()` 中添加以下代码:

tracker?.let {
if (it.isSelected(position.toLong()) ) {
it.select(position.toLong())
//changing the color of the clicked/selected item to light gray
//parent.setBackgroundColor( ContextCompat.getColor(context, R.color.extra_light_gray))
} else {
it.deselect(position.toLong())
// set color white
//parent.setBackgroundColor( ContextCompat.getColor(context, R.color.white))
}
}

关于android - 如何在 androidx.recyclerview.widget 中使用 androidx.recyclerview.selection。或者如何在 android 中使用 kotlin 在 recyclerview 中选择一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442809/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com