java - 如何获取ChipGroup精选芯片?

标签 java android material-components-android material-components android-chips

我在网上搜索了很多,但找不到确切的解决方案。这是我上次尝试的链接。 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());
                }
            }
        }
    });
}

这是输出 enter image description here

build.gradle(Module.app) 详细信息 enter image description here

最佳答案

从版本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/

相关文章:

java - 如何遍历 HashMap 的所有内容

android - TextInputLayout boxBackgroundColor 在 'com.google.android.material:material:1.1.0-alpha02' 之后不起作用

android - 如何在主题中全局更改android按钮文本颜色

java - Gradle 代理配置

java - 当屏幕太大时出现错误

java - 绩效十亿计数器

java - XML 中的 backgroundTint 不会更改 BottomActionBar 的颜色,即使最小 API >= 21

java - 热衷于使用 Jersey 和 Netbeans 编辑 JSON 对象输出?

java - 使用 DOZER 进行映射,无需设置方法

android - adb 永远等待运行模拟器