且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android:正确删除视图并将其添加到recyclerView

更新时间:2023-12-02 23:27:52

RecyclerViews背后的想法是,您可以将在onCreateViewHolder()中提供的视图持有者重用于同一viewType的视图.这种行为是使RecyclerViews高效的原因-膨胀视图的成本很高,而运行findViewById的成本也很高.

The idea behind RecyclerViews is that the view holder you provide in onCreateViewHolder() may be reused for views of the same viewType. This behavior is what makes RecyclerViews efficient - it is expensive to inflate views, and expensive to run findViewById.

您没有覆盖getItemViewType,因此您的RecyclerView仅具有一种视图类型-即,当您滚动浏览多个视图并删除/添加视图时,ViewHolders可以***地在彼此之间进行回收.

You did not override getItemViewType so your RecyclerView only has one viewtype -- i.e. your ViewHolders are free to be recycled amongst each other as you scroll across many views, and delete/add views.

那么您的代码中发生了什么?当您删除第二个视图时,其ViewHolder将被回收,并发送回回收器视图池.当您添加视图编号6时,回收者视图使用编号2中的回收视图支架.因此,永远不会调用onCreateViewHolder(因为还有一个额外的视图要回收!).但是,会调用onBindViewHolder .因此,添加一种方法来更新ViewHolder显示的数据:

So what is happening in your code? When you delete view number two, its ViewHolder is recycled, and sent back to the recycler view pool. When you add view number 6, the recycler view uses the recycled view holder from number 2. Thus, onCreateViewHolder is never called (because there was an extra view to recycle!). However, onBindViewHolder is called. So add a method to update the data displayed by the ViewHolder:

 public void setData(final int position) {
    eventName.setText(String.format("", position));
    theLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (position == 1){
                addItem("");
            }else {
                removeItem(position);
            }
        }
}

并在onBindViewHolder中调用此方法:

and call this method in onBindViewHolder:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
     holder.setData(position);
}