1、首先,确保您已经添加了BaseQuickAdapter和RecyclerView的依赖项。您可以在项目的build.gradle文件中添加以下依赖项:
- dependencies {
- implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4'
- implementation 'androidx.recyclerview:recyclerview:1.2.1'
- }
2、创建一个数据模型类来表示每个列表项的数据。例如,假设您有一个名为Item的数据类:
- public class Item {
- private String name;
- private boolean isSelected;
-
- public Item(String name) {
- this.name = name;
- this.isSelected = false;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean isSelected() {
- return isSelected;
- }
-
- public void setSelected(boolean selected) {
- isSelected = selected;
- }
- }
3、创建一个Adapter类,继承自BaseQuickAdapter
- public class ItemAdapter extends BaseQuickAdapter<Item, BaseViewHolder> {
-
- public ItemAdapter(@Nullable List<Item> data) {
- super(R.layout.item_layout, data);
- }
-
- @Override
- protected void convert(BaseViewHolder helper, Item item) {
- helper.setText(R.id.text_view, item.getName());
- // 设置选中状态的背景色
- if (item.isSelected()) {
- helper.itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.selected_color));
- } else {
- helper.itemView.setBackgroundColor(Color.TRANSPARENT);
- }
- }
-
- public void setItemSelected(int position) {
- for (int i = 0; i < getData().size(); i++) {
- getData().get(i).setSelected(i == position);
- }
- notifyDataSetChanged();
- }
- }
4、在您的Activity或Fragment中,初始化RecyclerView和Adapter,并设置默认选择第一个项:
- public class MainActivity extends AppCompatActivity {
-
- private RecyclerView recyclerView;
- private ItemAdapter adapter;
- private List<Item> itemList = new ArrayList<>();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- recyclerView = findViewById(R.id.recycler_view);
- recyclerView.setLayoutManager(new LinearLayoutManager(this));
-
- // 初始化数据
- for (int i = 0; i < 10; i++) {
- itemList.add(new Item("Item " + (i + 1)));
- }
-
- // 创建Adapter并设置默认选中第一个项
- adapter = new ItemAdapter(itemList);
- adapter.setItemSelected(0);
-
- recyclerView.setAdapter(adapter);
-
- // 设置RecyclerView的点击事件
- adapter.setOnItemClickListener((adapter, view, position) -> {
- adapter.setSelected(position);
- });
- }
- }