【问题标题】:Why onCheckedChanged() for RadioButton doesn't get raised in android?为什么 RadioButton 的 onCheckedChanged() 不会在 android 中引发?
【发布时间】:2014-05-21 12:05:37
【问题描述】:

我有一个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;
}

【问题讨论】:

  • 您在屏幕上拥有的广播组与您向我们展示的不同。

标签: java android onclick radio-button oncheckedchanged


【解决方案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,但在您使用rootView 检索的 RadioGroup 上附加OnCheckedChangeListener。应该是

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

而不是

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

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

【讨论】:

  • 感谢百万人。正是你所说的。在删除 l.addView() 之前我也遇到了一个异常。
猜你喜欢
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2014-12-11
相关资源
最近更新 更多