在RecyclerView中实现单选功能可以通过以下步骤完成:
下面是一个示例代码:
// 数据模型类
public class ItemModel {
private String name;
private boolean isSelected;
public ItemModel(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;
}
}
// 自定义适配器类
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ItemModel> itemList;
private OnItemSelectedListener listener;
public MyAdapter(List<ItemModel> itemList, OnItemSelectedListener listener) {
this.itemList = itemList;
this.listener = listener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ItemModel item = itemList.get(position);
holder.nameTextView.setText(item.getName());
holder.itemView.setSelected(item.isSelected());
holder.itemView.setOnClickListener(v -> {
// 更新选中状态
item.setSelected(true);
// 通知适配器和其他相关组件
listener.onItemSelected(position);
notifyDataSetChanged();
});
}
@Override
public int getItemCount() {
return itemList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.nameTextView);
}
}
public interface OnItemSelectedListener {
void onItemSelected(int position);
}
}
// 在Activity或Fragment中使用
public class MainActivity extends AppCompatActivity implements MyAdapter.OnItemSelectedListener {
private RecyclerView recyclerView;
private MyAdapter adapter;
private List<ItemModel> itemList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化数据
itemList = new ArrayList<>();
itemList.add(new ItemModel("Item 1"));
itemList.add(new ItemModel("Item 2"));
itemList.add(new ItemModel("Item 3"));
// 初始化RecyclerView和适配器
recyclerView = findViewById(R.id.recyclerView);
adapter = new MyAdapter(itemList, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
@Override
public void onItemSelected(int position) {
// 处理单选事件
for (int i = 0; i < itemList.size(); i++) {
if (i != position) {
itemList.get(i).setSelected(false);
}
}
}
}
这样,当用户点击列表项时,该项将被选中,并且其他项将取消选中状态。你可以根据实际需求进行修改和扩展。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云