Android development multi-selection list and echo selected content

problem background

In the daily development and learning process of Android, we often encounter scenarios that require a multi-select list and display the selected content. This article will introduce a solution for Android to implement a multi-select list and echo the selected content.

problem analysis

Without further ado, let’s start with the effect:
insert image description here

Idea analysis:
A vertical list displays the content to be selected, and a horizontal list is used to display the selected content. Clicking on the item in the list to be selected and the item in the selected list can update the page content.

problem solved

Not much to say, just go to the code.
(1) Page layout file, the code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MultiChooseActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="18sp"
            android:text="已选择:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/chosedList"
            android:layout_gravity="center_vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <View
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"
        android:layout_width="match_parent"
        android:background="@color/black"
        android:layout_height="1dp"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/choicesList"
        android:layout_width="150dp"
        android:layout_height="wrap_content"/>
</LinearLayout>

(2) The activity code is as follows:

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.baorant.multichoosecomponent.adapter.Callback;
import com.baorant.multichoosecomponent.adapter.ChoosedAdapter;
import com.baorant.multichoosecomponent.adapter.MultiChooseAdapter;
import com.baorant.multichoosecomponent.databinding.ActivityMultiChooseBinding;
import com.baorant.multichoosecomponent.entity.ChoiceBean;

import java.util.ArrayList;
import java.util.List;

public class MultiChooseActivity extends AppCompatActivity {
    ActivityMultiChooseBinding binding;
    MultiChooseAdapter multiChooseAdapter;
    ChoosedAdapter choosedAdapter;

    /**
     * 所有选项
     */
    List<ChoiceBean> choiceBeans = new ArrayList<>();
    /**
     * 已选择列表
     */
    List<ChoiceBean> choseBeans = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        initData();
    }

    private void initView() {
        binding = ActivityMultiChooseBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        binding.choicesList.setLayoutManager(linearLayoutManager);
        multiChooseAdapter = new MultiChooseAdapter(this, choiceBeans, new Callback() {
            @Override
            public void callback(ChoiceBean data) {
                if (choiceBeans == null || choosedAdapter == null) {
                    return;
                }
                if (data.isBtnStatus()) {
                    choseBeans.add(data);
                } else {
                    choseBeans.remove(data);
                }
                choosedAdapter.notifyDataSetChanged();
            }
        });
        binding.choicesList.setAdapter(multiChooseAdapter);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        binding.chosedList.setLayoutManager(linearLayoutManager1);
        choosedAdapter = new ChoosedAdapter(this, choseBeans, new Callback() {
            @Override
            public void callback(ChoiceBean data) {
                for (ChoiceBean choiceBean : choiceBeans) {
                    if (choiceBean.getTitle().equals(data.getTitle())) {
                        choiceBean.setBtnStatus(false);
                        break;
                    }
                }
                multiChooseAdapter.notifyDataSetChanged();
            }
        });
        binding.chosedList.setAdapter(choosedAdapter);
    }

    private void initData() {
        for(int i = 0; i < 10; i++) {
            choiceBeans.add(new ChoiceBean("第" + i + "个选项"));
        }
        multiChooseAdapter.notifyDataSetChanged();
    }
}

(3) The list to be selected corresponds to the adapter, the code is as follows:

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.baorant.multichoosecomponent.R;
import com.baorant.multichoosecomponent.entity.ChoiceBean;

import java.util.List;

/**
 * 多选adapter
 */
public class MultiChooseAdapter extends RecyclerView.Adapter<MultiChooseAdapter.ListViewHolder> {

    /**
     * 数据源
     */
    private List<ChoiceBean> dataList;
    private Context context;
    private Callback callback;

    public MultiChooseAdapter(Context context, List<ChoiceBean> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    public MultiChooseAdapter(Context context, List<ChoiceBean> dataList, Callback callback) {
        this.context = context;
        this.dataList = dataList;
        this.callback = callback;
    }

    @NonNull
    @Override
    public ListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_mulit_choose, null);
        return new ListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ListViewHolder holder, int position) {
        holder.tvTitle.setText(dataList.get(position).getTitle());
        if (dataList.get(position).isBtnStatus()) {
            holder.ivChoose.setImageResource(R.drawable.choose);
        } else {
            holder.ivChoose.setImageResource(R.drawable.not_choose);
        }
        holder.ivChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 把选中状态存到数据源类
                ChoiceBean data = dataList.get(position);
                // 取反状态值,赋值
                data.setBtnStatus(!data.isBtnStatus());
                // 刷新当前item
                notifyItemChanged(position);
                if (callback != null) {
                    callback.callback(data);
                }
            }
        });
    }

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

    public class ListViewHolder extends RecyclerView.ViewHolder {
        public TextView tvTitle;
        public ImageView ivChoose;

        public ListViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.title);
            ivChoose = itemView.findViewById(R.id.status);
        }
    }

}

(4) The adapter corresponding to the list has been selected, the code is as follows:

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.baorant.multichoosecomponent.R;
import com.baorant.multichoosecomponent.entity.ChoiceBean;

import java.util.List;

/**
 * 已选列表adapter
 */
public class ChoosedAdapter extends RecyclerView.Adapter<ChoosedAdapter.ListViewHolder> {

    /**
     * 数据源
     */
    private List<ChoiceBean> dataList;
    private Context context;
    private Callback callback;


    public ChoosedAdapter(Context context, List<ChoiceBean> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    public ChoosedAdapter(Context context, List<ChoiceBean> dataList, Callback callback) {
        this.context = context;
        this.dataList = dataList;
        this.callback = callback;
    }

    @NonNull
    @Override
    public ListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_choosed, null);
        return new ListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ListViewHolder holder, int position) {
        holder.tvTitle.setText(dataList.get(position).getTitle());
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callback != null) {
                    callback.callback(dataList.get(position));
                }

                dataList.remove(position);
                notifyDataSetChanged();
            }
        });
    }

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

    public class ListViewHolder extends RecyclerView.ViewHolder {
        public TextView tvTitle;
        public ImageView delete;

        public ListViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.title);
            delete = itemView.findViewById(R.id.delete);
        }
    }

}

(5) item_choosed.xml file, the code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MultiChooseActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        tools:text="标题" />

    <ImageView
        android:id="@+id/delete"
        android:layout_toEndOf="@id/title"
        android:src="@drawable/delete"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_centerVertical="true"/>
</RelativeLayout>

(6) item_mulit_choose.xml file, the code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="50dp"
    android:layout_height="20dp"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MultiChooseActivity">

    <TextView
        android:id="@+id/title"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        tools:text="标题" />

    <ImageView
        android:id="@+id/status"
        android:layout_alignParentEnd="true"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        tools:src="@drawable/choose"/>
</RelativeLayout>

(7) Option entity class, the code is as follows:

/**
 * 选项实体类
 */
public class ChoiceBean {
    private String title;
    // false代表未选中,true 选中
    private boolean btnStatus = false;

    public ChoiceBean(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isBtnStatus() {
        return btnStatus;
    }

    public void setBtnStatus(boolean btnStatus) {
        this.btnStatus = btnStatus;
    }
}


conclusion of issue

This article introduces a solution for Android to implement a multi-selection list and echo the selected content. Interested students can further study it.

Guess you like

Origin blog.csdn.net/weixin_39033300/article/details/130794228