仅单击一个时,RecyclerView的第一项和最后一项将被更改 [英] RecyclerView first and last item are changed, when clicking only one

查看:95
本文介绍了仅单击一个时,RecyclerView的第一项和最后一项将被更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用recyclerview来显示一个可以选择的兴趣列表.点击第一项,也会选择最后一项

I'm using a recyclerview to display a list of interests one could choose from. Clicking the very first item makes the very last item also selected

选择第一项:

还选择了最后一项:

选择是通过以下代码完成的:

The selection is done with this code:

@Override
public InterestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    TextView v = (TextView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.interests_textview, parent, false);
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView textView = (TextView) v;
            if (textView.getCompoundDrawables()[2] == null) {
                textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkmark, 0);
            } else {
                textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
        }
    });
    return new InterestViewHolder(v);
}

单击最后一个项目时,也会选择第一个项目.谁知道是什么原因造成的?

Also the very first item is also selected, when clicking the very last item. Who knows what could cause this?

推荐答案

您正在将布局放大为 TextView .将其更改为 View v ,它应该可以工作:

You are inflating a layout into a TextView. Change it to View v and it should work:

View v = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.interests_textview, parent, false);

此外,您还需要使用 findViewByID()以便从布局中获取正确的 TextView :

Also you need to use findViewByID() in order to get the correct TextView from your layout:

代替

TextView textView = (TextView) v;

执行此操作:

TextView textView = findViewById(<id of your textview in the layout>);

View 投射到 TextView 并不是您想要的.

Casting the View to a TextView is not what you want to do.

这篇关于仅单击一个时,RecyclerView的第一项和最后一项将被更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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