Recyleview有时会在顶部添加新项目

时间:2019-03-07 07:35:46

标签: android kotlin android-recyclerview recycler-adapter

单击前一个布局的加号按钮,我将向RecycleView添加新布局。首先,我要向模型类添加空数据,并将适配器设置为一项。单击该按钮之后,我需要添加第二项,依此类推。

问题是。首先,它可以工作并显示带有一个项目的recyclview。单击按钮后,第二个布局也将添加在第一个下面。但是第三次​​,如果我单击该按钮。它在Recycleview的顶部添加了一个新项。我需要生成一个垂直层次结构。

在onCreate上添加第一个数据

var arrayList:ArrayList<SubjectModel> = ArrayList()

        var model = SubjectModel()
        arrayList.add(model)

        var adapter = SubjectListAdapter(arrayList)

        var layoutManager  = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)

        rv_subject.layoutManager = layoutManager
        rv_subject.adapter = adapter

在适配器内部。我有一个加号按钮,它会垂直添加新项目。

      holder.img_delete_subject.setTag(position);
    holder.img_delete_subject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            if (if it is plus ) {

                holder.img_delete_subject.setImageResource(minus image);

                data.add(data.size(),new SubjectModel());
                notifyItemInserted((data.size() - 1));

            } else {

                data.remove(Integer.parseInt(view.getTag().toString()));
              notifyItemRemoved(Integer.parseInt(view.getTag().toString()));

            }


        }
    });

1 个答案:

答案 0 :(得分:1)

问题出在notifiyDataSetChanged()上。正如文档所述:

         * <p>This event does not specify what about the data set has changed, forcing
         * any observers to assume that all existing items and structure may no longer be valid.
         * LayoutManagers will be forced to fully rebind and relayout all visible views.</p>

将单个项目添加到列表时,您应该使用

notifyItemInsterted(position: Int)
        /**
         * Notify any registered observers that the item reflected at <code>position</code>
         * has been newly inserted. The item previously at <code>position</code> is now at
         * position <code>position + 1</code>.
         *
         * <p>This is a structural change event. Representations of other existing items in the
         * data set are still considered up to date and will not be rebound, though their
         * positions may be altered.</p>
         *
         * @param position Position of the newly inserted item in the data set