Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在androidx.recyclerview.widget中使用androidx.recyclerview.selection。或者如何在android中使用kotlin在recyclerview中选择项目?_Android_Kotlin_Android Recyclerview - Fatal编程技术网

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

如何在androidx.recyclerview.widget中使用androidx.recyclerview.selection。或者如何在android中使用kotlin在recyclerview中选择项目?,android,kotlin,android-recyclerview,Android,Kotlin,Android Recyclerview,我创建了一个水平回收器视图,其中包含已加载的项目。之后,我需要选择该项目并执行单击事件。到目前为止(代码如下所示),现在我想更改单击项目的颜色,其余项目应取消选中。如果我没有正确询问,请道歉 这一切都是使用Kotlin的Androidx Recyclerview构建的。给你!我正在寻找一个解决方案来扩展它,用于选择项目并更改其颜色 用kotlin编码的Android活动 import androidx.appcompat.app.AppCompatActivity import androi

我创建了一个水平回收器视图,其中包含已加载的项目。之后,我需要选择该项目并执行单击事件。到目前为止(代码如下所示),现在我想更改单击项目的颜色,其余项目应取消选中。如果我没有正确询问,请道歉

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

用kotlin编码的Android活动



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);


    }


导入androidx.appcompat.app.appcompat活动
导入android.os.Bundle
导入android.view.view
导入android.view.WindowManager
导入androidx.recyclerview.widget.LinearLayoutManager
导入kotlinx.android.synthetic.main.activity\u示例*
导入androidx.recyclerview.widget.recyclerview
类SampleActivity:AppCompatActivity(){
val瓶子名称:ArrayList=ArrayList()
val瓶子\u img:ArrayList=ArrayList()
val瓶子类型:ArrayList=ArrayList()
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_示例)
添加瓶()
val adptr=瓶子接受器(瓶子名称、瓶子图像、瓶子类型);
瓶子\u list.adapter=adptr
val layoutManager=LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
val recyclerView=瓶子列表
RecycleView.setLayoutManager(layoutManager)
}
覆盖窗口焦点更改(hasFocus:Boolean){
super.onWindowFocusChanged(hasFocus)
如果(hasFocus){
hideSystemUI()
}
}
私人娱乐场所{
val decorView=window.decorView
decorView.SystemUI可见性=(
View.SYSTEM\u UI\u FLAG\u沉浸式
或View.SYSTEM\u UI\u FLAG\u布局\u稳定
或View.SYSTEM\u UI\u FLAG\u LAYOUT\u HIDE\u导航
或View.SYSTEM\u UI\u FLAG\u LAYOUT\u全屏显示
或View.SYSTEM\u UI\u FLAG\u HIDE\u导航
或View.SYSTEM\u UI\u FLAG\u全屏显示
)
添加标志(WindowManager.LayoutParams.FLAG\u保持屏幕打开);
}
乐趣{
瓶子名称。添加(“Coca1”);
瓶子名称。添加(“Coca2”);
瓶子名称。添加(“Coca3”);
瓶子名称。添加(“Coca4”);
瓶子名称。添加(“Coca5”);
瓶子名称。添加(“Coca6”);
瓶子名称。添加(“Coca7”);
瓶子名称。添加(“Coca8”);
瓶型添加(“冷饮”);
瓶型添加(“冷饮”);
瓶型添加(“冷饮”);
瓶型添加(“冷饮”);
瓶型添加(“冷饮”);
瓶型。添加(“葡萄酒”);
瓶型。添加(“葡萄酒”);
瓶型。添加(“葡萄酒”);
瓶内添加(R.可抽出式coca1);
瓶内添加(R.可抽出coca2);
瓶内添加(R.可抽出式coca3);
加瓶(R.可抽出式coca4);
瓶内添加(R.可抽出式coca5);
瓶内添加(R.可拉拔coca6);
瓶内添加(R.可抽出式coca7);
添加瓶子(R.可抽出式coca8);
}
使用Kotlin编码的瓶子适配器


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"
    }
}



导入android.content.Context
导入android.util.Log
导入android.view.LayoutInflater
导入android.view.ViewGroup
导入android.view.view
导入android.widget.ArrayAdapter
导入android.widget.ImageView
导入android.widget.TextView
导入androidx.recyclerview.widget.LinearLayoutManager
导入kotlinx.android.synthetic.main.battle\u list\u item.view*
导入androidx.recyclerview.widget.recyclerview
类瓶装适配器(专用val数据集:ArrayList,专用val数据集2:ArrayList,专用val数据集3:ArrayList):
RecyclerView.Adapter(){
/**
*提供对正在使用的视图类型的引用(自定义ViewHolder)
*/
类ViewHolder(v:视图):RecyclerView.ViewHolder(v){
val textView:textView
val imageView:imageView
val textView2:TextView
初始化{
//定义ViewHolder视图的单击侦听器。
v、 setOnClickListener{
Log.d(标记“Element$adapterPosition clicked.”)
//我已经尝试过了,但它没有给我机会为所选项目选择颜色
if(v.id==适配器位置){
v、 setBackgroundResource(R.可抽出。选择瓶卡);
}
否则{
v、 setBackgroundResource(R.可抽出式瓶卡);
}
}
textView=v.findviewbyd(R.id.battle\u list\u text)
imageView=v.findViewById(R.id.Battle\u列表\u img)
textView2=v.findViewById(R.id.Battle\u列表\u子文本)
}
}
//创建新视图(由布局管理器调用)
覆盖创建ViewHolder(viewGroup:viewGroup,viewType:Int):ViewHolder{
//创建一个新视图。
val v=LayoutInflater.from(viewGroup.context)
.充气(右布局瓶列表项,视图组,假)
返回视窗支架(v)
}
//替换视图的内容(由布局管理器调用)
覆盖BindViewHolder(viewHolder:viewHolder,位置:Int){
Log.d(标记“元素$positionset.”)
//在此位置从数据集中获取元素并替换视图的内容
//有了这个元素
viewHolder.textView.text=数据集[位置]
viewHolder.textView2.text=数据集3[位置]
viewHolder.imageView.setImageResource(数据集2[位置])
}
//返回数据集的大小(由布局管理器调用)
重写getItemCount()=dataSet.size
伴星{
private val TAG=“CustomAdapter”
}
}
我期待一个更好的解决方案
implementation "androidx.recyclerview:recyclerview-selection:1.0.0
private var tracker: SelectionTracker<Long>? = null

    fun setTracker(tracker: SelectionTracker<Long>?) {
        this.tracker = tracker
    }
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
            }
        })
}
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
        }
}
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
        }
}
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))
    }
}