我在网上搜索了很多,但找不到确切的解决方案。这是我上次尝试的链接。 Get selected Chips from a ChipGroup
我想在单击按钮时从芯片组中获取选定的芯片。
该函数包含在RecyclerView中显示名称的信息
private void getNames() {
List<String> names = Arrays.asList(getResources().getStringArray(R.array.names));
int count = 0;
for ( String name : names){
list.add(new Names(name));
count++;
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
namesAdapter = new NamesAdapter(MainActivity.this, list);
recyclerView.setAdapter(namesAdapter);
}
当点击RecyclerView项时,将一个芯片添加到ChipGroup中,这是函数
public void onItemSelected(Names name) {
Chip chip = new Chip(this);
chip.setText(name.getName());
chip.setCloseIconVisible(true);
chip.setCheckable(false);
chip.setClickable(false);
chip.setOnCloseIconClickListener(this);
chipGroup.addView(chip);
chipGroup.setVisibility(View.VISIBLE);
}
This is the image of displaying chips in ChipGroup
从 ChipGroup 获取值的函数
public void getChipGroupValues(){
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ChipGroup chipGroup = findViewById(R.id.chipGroup);
for (int i=0; i<chipGroup.getChildCount();i++){
Chip chip = (Chip)chipGroup.getChildAt(i);
Log.i("outside if ", i+ " chip = " + chip.getText().toString());
if (chip.isChecked()){
Log.i("inside if ", i+ " chip = " + chip.getText().toString());
textView.setText(chip.getText().toString());
}
}
}
});
}
最佳答案
从版本1.2.0开始,您可以使用方法chipGroup.getCheckedChipIds()
List<Integer> ids = chipGroup.getCheckedChipIds();
for (Integer id:ids){
Chip chip = chipGroup.findViewById(id);
//....
}
1.1.0 的旧答案:
目前没有直接的 API 来获取所选芯片。
不过,您可以遍历 ChipGroup
的子级并检查 chip.isChecked()
。
ChipGroup chipGroup = findViewById(R.id.....);
for (int i=0; i<chipGroup.getChildCount();i++){
Chip chip = (Chip)chipGroup.getChildAt(i);
if (chip.isChecked()){
//this chip is selected.....
}
}
关于java - 如何获取ChipGroup精选芯片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58224630/