【问题标题】:How to get reference of radiobutton that is added dynamically in onclicklistener?如何获取在 onclicklistener 中动态添加的单选按钮的引用?
【发布时间】:2016-12-13 14:59:52
【问题描述】:

我确实有一个片段膨胀包含单个按钮的布局。我在onCreateView() 方法中动态添加了radiogroupradiobuttons。但问题出在该按钮的onclicklistener 中。在检索在 radioGroup 中签入的 radiobutton 文本时,我确实得到了 nulpointerexception

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v =  inflater.inflate(R.layout.variant_choose,null);

    Button button = (Button) v.findViewById(R.id.apply_variant_button);

    LinearLayout ll = (LinearLayout) v.findViewById(R.id.layout_for_radiobuttons_in_variants);

    final RadioGroup rg = new RadioGroup();
    rg.setId(View.generateViewId());
    rg.setOrientation(LinearLayout.HORIZONTAL);
    RadioButton rb[] = new RadioButton[5];
    for(int j=0;j<5;j++){

            rb[j] = new RadioButton(getActivity());
            rb[j].setId(View.generateViewId());
            rb[j].setText(j);
            rg.addView(rb[j]);       

    }

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                RadioButton rb1 = (RadioButton) v.findViewById(rg.getCheckedRadioButtonId());

                String str1 = (String) rb1.getText();

        }
    });

  return v;
}

View v 包含动态创建的radiogroup 和按钮直到onCreateView。但后来在onclicklistener 并非如此。它只包含在 xml 文件中定义的按钮?这可能是什么原因?如何获取已选中的radiobutton 的文本?

【问题讨论】:

  • 你应该使用标签而不是 ids。
  • 我可以指向这篇 SO 帖子:stackoverflow.com/questions/8460680/… 我认为它可以帮助您更好地理解 ID,并帮助您发现一些以编程方式实现它们的方法。

标签: java android android-studio android-fragments


【解决方案1】:

我相信您的RadioGroup 中没有选中的RadioButton,因此rg.getCheckedRadioButtonId() 返回-1,然后findViewById 返回null

在填充数组后尝试rb[0].setChecked(true);

【讨论】:

  • 是的,这可能是一个原因。但我检查了radiobutton。它在 onclicklistener 范围之外可以正常工作,但在 onClick method 中则不行
猜你喜欢
  • 2014-09-10
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 2017-11-30
  • 1970-01-01
相关资源
最近更新 更多