【问题标题】:getText() always return empty string from dynamically created Chip component?getText() 总是从动态创建的芯片组件返回空字符串?
【发布时间】:2019-06-12 16:53:16
【问题描述】:

我正在尝试根据来自某些计算的字符串的 ArrayList 动态创建一些选择芯片组件,以下是创建芯片并将它们添加到布局 XML 文件中创建的 ChipGroup 的代码。

        if (mChipGroup.getChildCount() == 0 ){
            int i = 0;
            for (Classifier.Recognition res: results){
                Chip resultChip = new Chip(getDialog().getContext());
                ChipDrawable chipDrawable =
                        ChipDrawable.createFromAttributes(
                                getActivity(),
                                null,
                                0,
                                R.style.Widget_MaterialComponents_Chip_Choice);
                resultChip.setId(i++);
                resultChip.setChipDrawable(chipDrawable);
                resultChip.setText(res.getTitle());
                mChipGroup.addView(resultChip);
            }
        }

芯片与文本一起正确显示,但是当我尝试在芯片上调用 getText() 时,它总是返回空字符串,而不是芯片包含的文本。我通过在 ChipGroup 上设置 OnCheckedChangeListener 并用文本制作一个 Toast 来测试这一点(尽管它不起作用)。当我尝试仅显示 checkedId 时,它可以工作。


        mChipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(ChipGroup group, int checkedId) {
                Chip chip = group.findViewById(checkedId);
                if(chip != null){
                    Toast.makeText(getContext(), chip.getText().toString(),Toast.LENGTH_SHORT).show();
                }
            }
        });

我目前的解决方法是让一个变量保存数组结果并使用ArrayList.get(selectedChipId.getTitle())。但不要认为它应该是那样的

我还发现它能够从添加到布局文件的芯片中获取文本,但不能从运行时添加的芯片中获取文本。尝试了 1.1.0/alpha06 和 1.1.0/alpha07 版本,但没有运气。如果可能的话,想得到一些建议。非常感谢你。

【问题讨论】:

  • 你能通过点击得到正确的筹码ID吗?你也有ChipGroup吗?看看这个例子:android--code.blogspot.com/2019/01/…
  • @payam 嗨,是的,我可以获得正确的芯片 ID,并且在获取文本时参考了多个示例,但仍然没有运气。我目前的解决方法是让一个变量保存数组结果并使用 ArrayList.get(selectedChipId.getTitle()). 但不认为它应该是这样的

标签: java android material-design android-chips


【解决方案1】:

因此,根据here 和here 的回答,这似乎是一个错误。当前的解决方法是改用((ChipDrawable) chip.getChipDrawable()).getText()。

猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2016-12-16
  • 2019-07-25
  • 1970-01-01
相关资源
最近更新 更多