使用RecyclerView时如何处理与视图交互时的UI更改? [英] How to handle UI changes from interaction with a view when using a RecyclerView?

查看:182
本文介绍了使用RecyclerView时如何处理与视图交互时的UI更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个RecyclerView,它将具有不同类型的视图,则可以根据项目类型(例如,

If we have a RecyclerView that will have views of different type we can inflate the view we need based on an item type e.g.

@Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
        View view = null;
        switch (type) {
            case TYPEX:  
               view = LayoutInflater
                    .from(viewGroup.getContext())
                    .inflate(R.layout.typex, viewGroup, false);
                    return new ViewHolderX(view);
            case TYPEY:
                view = LayoutInflater
                    .from(viewGroup.getContext())
                    .inflate(R.layout.typey, viewGroup, false);
                return new ViewHolderY(view);
        }
        return null;
    }

到目前为止,一切都很好.然后,这些视图可在ViewHolder

So far so good. The views then are reusable in the ViewHolder

问题:
如果TYPEX视图具有一个按钮,则按下该按钮会更改视图中的某些内容,例如背景颜色,这意味着在回收视图时,用户从未按过按钮的其他项目的颜色将有所不同.
由于与视图必须从适配器显示的数据的任何条件都无关,该如何解决呢?

Question:
If TYPEX view has a button that on press changes something in the view e.g. the background color, this means that when the view is recycled the color will be different for other items that the user never pressed the button for.
How can this be addressed since it would not be related to any condition of the data that the view has to display from the adapter?

推荐答案

您应将属性[背景颜色]存储在模型中,并据此做出决定.

You should store your Property [background color] inside model and make decision based on that.

class Model {

    ...

    private int backgroundColor = 0xFFFFFF;

    public int getBackgroundColor() {
        return backgroundColor;
    }

    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    ...

}

请单击此处并更新背景色.

Handle click here and update background color.

@Override
public void onBindViewHolder(@NonNull final SuggestionHomeAdapter.ViewHolder holder, final int position) {

    final Model model = modelItems.get(position);

    holder.rootView.setBackgroundColor(model.getBackgroundColor());

    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(model.getBackgroundColor() != 0xFFFF0000){
                model.setBackgroundColor(0xFFFF0000);
                notifyItemChanged(position);
            }
        }
    });
}

它通过位置而不是视图持续存在于模型中.因此,只有那些受到用户点击的项目才会受到影响.谢谢

It persists with model by position not view. So only those item affected that are click by user. Thanks

这篇关于使用RecyclerView时如何处理与视图交互时的UI更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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