【问题标题】:RadioGroup and checkedIdRadioGroup 和checkedId
【发布时间】:2017-05-16 15:45:33
【问题描述】:

我上周刚开始学习,我对书上的RadioGroup 有一些疑问。


radioGroup.clearCheck();

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);

                switch (rb.getId()) {

                    case R.id.radioButtonLondon:
                        tClock.setTimeZone("Europe/London");
                        break;

                    case R.id.radioButtonBeijing:
                        tClock.setTimeZone("CST6CDT");
                        break;


                    case R.id.radioButtonNewYork:
                        tClock.setTimeZone("America/New_York");
                        break;
                }
                // End switch block

            //}
        }
    });

  1. 在我的书上写着RadioButton rb = (RadioButton) group.findViewById(checkedId);is used to

"获取checkId所引用的实际对象的引用, 然后我们可以检索我们当前使用的熟悉的 ID 选中的单选按钮,我们现在有一个参考存储在 rb。”

我对这个解释很困惑

  1. 这行RadioButton rb = (RadioButton) group.findViewById(checkedId); 有必要吗?我试图隐藏这一行并将switch (rb.getId()) 更改为switch(checkedId),一切仍然正常。

谢谢!

【问题讨论】:

标签: java android radio-button android-radiogroup


【解决方案1】:

看到你只更新 "tClock" 那么你是对的,那条线没有必要。如果出于某种其他原因,您需要调用单选按钮的任何可用方法,那将是必要的。

【讨论】:

    【解决方案2】:

    不要定义单选按钮。在 setOnCheckedChangeListener 本身中,您将获得单选按钮 id。删除 RadioButton rb = (RadioButton) group.findViewById(checkedId);

    您的代码应如下所示:

     radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
    
                switch (checkedId) {
    
                    case R.id.radioButtonLondon:
                        tClock.setTimeZone("Europe/London");
                        break;
    
                    case R.id.radioButtonBeijing:
                        tClock.setTimeZone("CST6CDT");
                        break;
    
    
                    case R.id.radioButtonNewYork:
                        tClock.setTimeZone("America/New_York");
                        break;
                }
                // End switch block
    
            //}
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 2019-03-06
      • 1970-01-01
      • 2021-06-05
      • 2018-05-28
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多