要在 Firebase 中更改 ListViewItems 的布尔值,您需要执行以下步骤:
Item
的 ListViewItems 的布尔值,请创建一个名为 Item
的类:public class Item {
private String id;
private String name;
private boolean isSelected;
public Item() {
// Default constructor required for calls to DataSnapshot.getValue(Item.class)
}
public Item(String id, String name, boolean isSelected) {
this.id = id;
this.name = name;
this.isSelected = isSelected;
}
// Getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public boolean isSelected() { return isSelected; }
public void setSelected(boolean selected) { isSelected = selected; }
}
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("items");
ArrayAdapter
或自定义适配器。以下是使用 ArrayAdapter
的示例:List<Item> itemList = new ArrayList<>();
ArrayAdapter<Item> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, itemList);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
itemList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Item item = snapshot.getValue(Item.class);
itemList.add(item);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// Handle possible errors.
}
});
// 假设您有一个方法来处理 ListView 的点击事件
public void onItemClick(int position) {
Item item = itemList.get(position);
item.setSelected(!item.isSelected());
databaseReference.child(item.getId()).setValue(item);
adapter.notifyDataSetChanged();
}
现在,当您点击 ListView 中的某个项目时,它的布尔值将在 Firebase 数据库中更新,并刷新 ListView 以显示更改。
领取专属 10元无门槛券
手把手带您无忧上云