在RecyclerView中选择项目 [英] Select items in RecyclerView

查看:84
本文介绍了在RecyclerView中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人问过类似的问题,但我无法让他们中的任何一个起作用.

Similar question have been asked, but i can't get any of them work.

我想要的是在RecyclerView中选择项目,更改该项目视图的背景,并存储所选项目的位置.

What i want is to select item in RecyclerView, change the background of that item view, and store the position of item selected.

主要问题是您拥有onCreateViewHolder(在适配器中),onBindViewHolder(在适配器中)和ViewHolder构造函数,并且每个人都在使用不同的方法. 现在,我什至不知道将onClickListener放在哪里(在以前的项目中,我将其放在ViewHolder中),因为人们也在建议另外两种方法.

The main problem is that you have onCreateViewHolder (in adapter), onBindViewHolder (in adapter) and ViewHolder constructor and everybody is working with different methods. Now, i don't even know where to put onClickListener (in previous projects i've put it in ViewHolder), because people are suggesting the other two methods too.

我的想法是将每个ViewHolder(或View)存储在列表中,这样我就可以引用每一行,并从那里更改背景.但这对我不起作用,因为当我尝试从三个位置(onCreateVH,onBindVH,VH类)中的任何一个添加到View(或ViewHolders)列表时,我的应用由于某种原因崩溃(例如空指针).

My idea was to store each ViewHolder (or View) in list, so i can have reference to each row, and change the background from there. But that didn't work for me, because when i try to add to list of View(or ViewHolders), from any of three places (onCreateVH, onBindVH, VH class), my app crashes for some reason (null pointer ex).

有什么建议吗?在哪里以及如何实施?

Any suggestions? Where and how to implement it?

推荐答案

使全局变量存储位置并处理ViewHolder中的单击侦听器. Onclick项目,更改全局位置值,如

Make global variable to store position and handle click listener in ViewHolder. Onclick of item, change the global position value like

textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        globalPosition=getAdapterPosition();
        notifyDataSetChanged();
    }
});

然后在onBindViewHolder

if(postion==globalPosition)
{
    //change color like
    textview.setTextColor(Color.RED);
}
else
{
    //revert back to regular color 
    textview.setTextColor(Color.WHITE);
}

使用此代码,您单击的项目将变为红色,而所有其他符号将变为白色.

with this code, the item you clicked get red colored and all other wiil be in white.

这篇关于在RecyclerView中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆