如何在RecyclerView中实现多选?

Heg*_*kar 51 android multi-select android-recyclerview

这是使用ListView实现的

ListView有一个多选模式,我应该用什么来实现使用RecyclerView?如何处理onItemCheckedStateChanged?我查了一下,但是我无法理解这一点.任何代码片段或实现它的示例项目都会很棒.提前致谢.

Sha*_*nth 95

我知道回答这个问题有点晚了.我不知道它是否符合OP的要求.但这可能对某人有所帮助.我用一个简单的技巧实现了这个多选RectyclerView.这是我的代码.

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEE">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

item_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    android:background="#FFF"
    android:clickable="true" 
    android:orientation="vertical">

   <TextView
      android:id="@+id/text_view"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:padding="10dp"
      tools:text="TextView" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

item_row.xml android:clickable="true"是很重要的.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private List<Model> mModelList;
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new RecyclerViewAdapter(getListData());
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);
    }

    private List<Model> getListData() {
      mModelList = new ArrayList<>();
      for (int i = 1; i <= 25; i++) {
          mModelList.add(new Model("TextView " + i));
      }
     return mModelList;
    }
}
Run Code Online (Sandbox Code Playgroud)

Model.java

public class Model {

    private String text;
    private boolean isSelected = false;

    public Model(String text) {
      this.text = text;
    }

    public String getText() {
      return text;
    }

    public void setSelected(boolean selected) {
      isSelected = selected;
    }


    public boolean isSelected() {
      return isSelected;
    }
}
Run Code Online (Sandbox Code Playgroud)

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    private List<Model> mModelList;

    public RecyclerViewAdapter(List<Model> modelList) {
      mModelList = modelList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
       return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        final Model model = mModelList.get(position);
        holder.textView.setText(model.getText());
        holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                model.setSelected(!model.isSelected());
                holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mModelList == null ? 0 : mModelList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private View view;
        private TextView textView;

        private MyViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            textView = (TextView) itemView.findViewById(R.id.text_view);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它是如何工作的? onBindViewHolder()方法将数据从ArrayList绑定到View对象.因此,按时将数据绑定到视图,它从ArrayList获取Model model = mModelList.get(position);具有当前位置的单个对象.现在我们需要检查是否选择了特定对象.像这样,

model.isSelected()
Run Code Online (Sandbox Code Playgroud)

返回true或者false.如果已选择该对象,我们需要更改row_item所选的背景颜色.为此,这里是代码

holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
Run Code Online (Sandbox Code Playgroud)

如果选中,则将背景颜色更改为cyanelse white.

为了选择我们需要使用setOnClickListener()方法.(这里我只使用了一个TextView.所以我正在进行点击事件TextView).这holder.view意味着整个单身item_row.Onclick将布尔值切换为truefalse.

 holder.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            model.setSelected(!model.isSelected());
            holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
        }
 });
Run Code Online (Sandbox Code Playgroud)

在托管RecyclerView的Activity或Fragment中,您可以获取所选的对象/项目

String text = "";
 for (Model model : mModelList) {
   if (model.isSelected()) {
     text += model.getText();
   }
 }
Log.d("TAG","Output : " + text);
Run Code Online (Sandbox Code Playgroud)

这是输出

产量

编辑1:限制用户只选择一个项目.

 private int lastSelectedPosition = -1;  // declare this variable
 ...
 // your code
 ...


 @Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    final Model model = mModelList.get(position);
    holder.textView.setText(model.getText());
    holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
    holder.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // check whether you selected an item

            if(lastSelectedPosition > 0) {
                mModelList.get(lastSelectedPosition).setSelected(false);
            }

            model.setSelected(!model.isSelected());
            holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);

            // store last selected item position 

            lastSelectedPosition = holder.getAdapterPosition();  
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我希望它会有所帮助.


Far*_*aev 6

那些提到的自定义多选实现的创建工作正常,但是当数据集很大时可能会出现性能问题。我强烈建议您阅读Google的“创建回收视图-启用列表项选择”部分。我已经列出了用于创建回收的链接 Android文档查看启用项目单击

  • 这个问题可能早于recyclerview-selection软件包,但对于现代应用程序,应使用此软件包来完成,并且就我而言,该答案应为公认的答案。 (3认同)
  • 不幸的是,关于如何使用它的文档很少。虽然这是一个很好的示例,但http://androidkt.com/recyclerview-selection-28-0-0/ (3认同)
  • 虽然此链接可以回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会变得无效。- [来自评论](/review/low-quality-posts/26397934) (3认同)

小智 5

public class RecyclerColorAdapter extends RecyclerView.Adapter<RecyclerColorAdapter.ViewHolder> {


        private final Activity activity;
        private final ArrayList<ColorItem> itemArrayList;


        public RecyclerColorAdapter(Activity activity, ArrayList<ColorItem> itemArrayList) {
            super();
            this.activity = activity;
            this.itemArrayList = itemArrayList;
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_color_recycleview, viewGroup, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int i) {
            holder.setIsRecyclable(true);

            final ColorItem colorItem = itemArrayList.get(i);


            holder.button_color.setText(colorItem.getColorName());

            holder.button_color.setBackgroundColor(colorItem.isSelected() ? Color.CYAN : Color.WHITE);

            holder.button_color.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    colorItem.setSelected(!colorItem.isSelected());
                    holder.button_color.setBackgroundColor(colorItem.isSelected() ? Color.CYAN : Color.WHITE);
                    if (colorItem.isSelected()){
                        arrayListColor.add("diamond_color[]="+colorItem.getValue()+"&");
                        Log.e("arrayListColor","---------"+arrayListColor);
                    }
                    else {
                        arrayListColor.remove("diamond_color[]="+colorItem.getValue()+"&");
                        Log.e("arrayListColor","---------"+arrayListColor);
                    }


                }
            });

        }

        @Override
        public int getItemCount() {

            return itemArrayList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            private Button button_color;

            public ViewHolder(View itemView) {
                super(itemView);
                itemView.setOnClickListener(this);
                button_color = (Button) itemView.findViewById(R.id.button_color);

            }

            @Override
            public void onClick(View v) {

            }

        }

    }
Run Code Online (Sandbox Code Playgroud)


civ*_*ida 5

无需创建模型类,我们可以在 recyclerview 中多项选择项目。在 recyclerview 适配器中使用此代码

holder.favplayIcon.setOnClickListener(View.OnClickListener {
                    if (!row_index.contains(position)) {
                        row_index.add(position)
                        holder.favplayIcon.setImageDrawable(
                            ResourcesCompat.getDrawable(resources, R.drawable.ic_starfilled, null ))

                    } else {
                        row_index.removeAt(row_index.indexOf(position))
                        holder.favplayIcon.setImageDrawable(
                   ResourcesCompat.getDrawable(resources,R.drawable.ic_starborder, null)
                        )  }
                })

///// put below code out of onclicklistener method of item
                if (!row_index.contains(position)) {

                    holder.favplayIcon.setImageDrawable(
                        ResourcesCompat.getDrawable(
                            resources,
                            R.drawable.ic_starborder,
                            null
                        )
                    )
} else {
                    holder.favplayIcon.setImageDrawable(
                        ResourcesCompat.getDrawable(
                            resources,
                            R.drawable.ic_starfilled,
                            null
                        )
                    )
Run Code Online (Sandbox Code Playgroud)