为什么用于RadioButton的onCheckedChanged()不会在android中引发?

时间:2014-04-08 16:34:25

标签: java android onclick radio-button oncheckedchanged

我有Fragment。它里面有两个单选按钮。我正在尝试创建一个TextView 此片段并根据RadioButton用户检查更改其内容。 您可以在下面看到我的代码。我的问题是当我点击单选按钮时没有任何反应/ 似乎没有toast消息和setText()被调用。 请帮帮我。 谢谢。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.activity_search, container,false);
    final LinearLayout l = (LinearLayout)inflater.inflate(R.layout.activity_search, container, false);
    final TextView tv = new TextView(container.getContext());
    tv.setText("Testing...");
    l.addView(tv);
    RadioGroup radios = (RadioGroup) rootView.findViewById(R.id.radios);
    radios.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            tv.setText("changedText");
            l.addView(tv);
            Toast.makeText(getActivity(), "zzzz", 2000).show(); 

            switch(checkedId) {
            case R.id.rbtn_sell:
                tv.setText("changedText");
                l.addView(tv);
                break;
            case R.id.rbtn_rent:
                RadioButton radioButton = (RadioButton) rootView.findViewById(checkedId);
                Toast.makeText(getActivity(), "zzzz" + radioButton.getText(), 2000).show(); 
                break;
            }
        }
    });
    return l;
}

1 个答案:

答案 0 :(得分:1)

  final View rootView = inflater.inflate(R.layout.activity_search, container,false);
  final LinearLayout l = (LinearLayout)inflater.inflate(R.layout.activity_search, container, false);

问题出在这里。您正在对同一布局进行两次充气并返回l,但请将OnCheckedChangeListener附加到您使用rootView检索的RadioGroup上。它应该是

 RadioGroup radios = (RadioGroup) l.findViewById(R.id.radios);

而不是

 RadioGroup radios = (RadioGroup) rootView.findViewById(R.id.radios);

同样在onCheckedChanged内,你应该移除l.addView,否则你的应用程序会崩溃,因为TextView已经作为父l