在 Android 中,要实现 DataGrid 的多选功能,你可以使用 RecyclerView 和 GridLayoutManager。以下是实现多选功能的步骤:
isSelected
来表示项目是否被选中。public class Item {
private String title;
private boolean isSelected;
public Item(String title) {
this.title = title;
this.isSelected = false;
}
// Getter and Setter methods
}
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<Item> itemList;
private Context context;
public ItemAdapter(Context context, List<Item> itemList) {
this.context = context;
this.itemList = itemList;
}
@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) {
Item item = itemList.get(position);
holder.title.setText(item.getTitle());
holder.itemView.setSelected(item.isSelected());
}
@Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.item_title);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Item currentItem = itemList.get(position);
currentItem.setSelected(!currentItem.isSelected());
notifyItemChanged(position);
}
}
});
}
}
}
RecyclerView recyclerView = findViewById(R.id.recycler_view);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3); // 3 columns
recyclerView.setLayoutManager(gridLayoutManager);
List<Item> itemList = new ArrayList<>();
// Add items to the itemList
ItemAdapter adapter = new ItemAdapter(this, itemList);
recyclerView.setAdapter(adapter);
现在,你的 DataGrid 应该已经实现了多选功能。当用户点击某个项目时,它将被选中或取消选中,并且其状态会在数据模型中更新。你可以根据需要自定义选中和未选中的样式。