在 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 應該已經實現了多選功能。當用戶點擊某個項目時,它將被選中或取消選中,并且其狀態會在數據模型中更新。你可以根據需要自定義選中和未選中的樣式。