Android 一个按钮实现列表数据单选全选功能 具体实现代码
时间: 2024-04-21 10:24:33 浏览: 124
当然!以下是一个简单示例的代码,展示了如何在Android中使用一个按钮实现列表数据的单选和全选功能:
```java
public class MainActivity extends AppCompatActivity {
private Button selectAllButton;
private ListView listView;
private CustomAdapter adapter;
private List<Item> itemList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectAllButton = findViewById(R.id.select_all_button);
listView = findViewById(R.id.list_view);
// 初始化数据列表
itemList = new ArrayList<>();
itemList.add(new Item("Item 1", false));
itemList.add(new Item("Item 2", false));
itemList.add(new Item("Item 3", false));
// 添加更多项...
adapter = new CustomAdapter(this, itemList);
listView.setAdapter(adapter);
selectAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean allSelected = true;
// 检查是否已经全部选中
for (Item item : itemList) {
if (!item.isSelected()) {
allSelected = false;
break;
}
}
// 根据当前状态选择全部或取消全部
if (allSelected) {
for (Item item : itemList) {
item.setSelected(false);
}
} else {
for (Item item : itemList) {
item.setSelected(true);
}
}
adapter.notifyDataSetChanged(); // 更新列表项的UI
}
});
}
// 数据适配器
private class CustomAdapter extends BaseAdapter {
private Context context;
private List<Item> itemList;
public CustomAdapter(Context context, List<Item> itemList) {
this.context = context;
this.itemList = itemList;
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item, parent, false);
TextView itemNameTextView = view.findViewById(R.id.item_name_text_view);
CheckBox itemCheckBox = view.findViewById(R.id.item_check_box);
Item item = itemList.get(position);
itemNameTextView.setText(item.getName());
itemCheckBox.setChecked(item.isSelected());
// 设置单选和全选的UI效果
if (item.isSelected()) {
view.setBackgroundColor(Color.GREEN);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
// 点击列表项时切换选中状态
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
item.setSelected(!item.isSelected());
notifyDataSetChanged(); // 更新列表项的UI
}
});
return view;
}
}
// 数据模型
private class Item {
private String name;
private boolean selected;
public Item(String name, boolean selected) {
this.name = name;
this.selected = selected;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
}
```
请注意,上述代码只是一个简单示例,您可能需要根据您的具体需求进行修改和调整。希望能帮到您!如果有任何问题,请随时提问。
阅读全文