【问题标题】:How to get the selected index of a RadioGroup in Android如何在 Android 中获取 RadioGroup 的选定索引
【发布时间】:2011-09-20 09:08:49
【问题描述】:

有没有一种简单的方法可以在 Android 中获取 RadioGroup 的选定索引,还是我必须使用 OnCheckedChangeListener 来监听更改并保留最后一个选定索引的内容?

示例 xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

如果用户选择option 3我要获取索引,2。

【问题讨论】:

    标签: java android xml radio-group


    【解决方案1】:

    您可以使用 OnCheckedChangeListener 也可以使用 getCheckedRadioButtonId()

    【讨论】:

      【解决方案2】:

      您可以参考单选组并使用getCheckedRadioButtonId () 获取选中的单选按钮ID。看看here

      RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);
      

      然后当你需要得到选中的单选选项时。

      int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
      if (checkedRadioButtonId == -1) {
          // No item selected
      }
      else{
          if (checkedRadioButtonId == R.id.radio_button1) {
              // Do something with the button
          }
      }
      

      【讨论】:

      • 是的,这是选中的单选按钮的id,但是单选按钮在单选组中的索引呢?
      • 我可以得到id,我想要索引,它们是不同的。
      • 索引是什么意思?是否在列表视图中?
      • 如果我在单选组中有 5 个单选按钮,并且用户选择了我想要获得的第三个单选按钮 2,即单选组中所选单选按钮的索引。这不是列表视图。
      • 只是为了澄清用户是否选择了您想要获得第二个按钮的第三个按钮?单选组和按钮没有索引。
      【解决方案3】:

      你应该可以做这样的事情:

      int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
      View radioButton = radioButtonGroup.findViewById(radioButtonID);
      int idx = radioButtonGroup.indexOfChild(radioButton);
      

      如果RadioGroup 包含其他视图(如TextView),则indexOfChild() 方法将返回错误的索引。

      要在RadioGroup 上获取选定的RadioButton 文本:

       RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
       String selectedtext = r.getText().toString();
      

      【讨论】:

      • 但是如果这些按钮没有设置android:id 属性怎么办?
      • @BP 当没有设置父级或单选按钮 ID 时,我对访问单选按钮有同样的疑问。
      • @neuront 只要您执行 radioGroup.findViewById(radioButtonID) 就可以了。 RadioGroup 确实将 1、2、3、4 等设置为视图的 ID,因此如果您在其上下文中搜索它们,它将起作用
      • 如果设置了默认(并且用户未触及)RadioButton,这将不起作用。
      • @NinjaCoding 如果你和我犯了同样的错误,你必须通过调用 radioGroup.check(selectedRadioButton.id) 来设置默认(初始)单选按钮,而不是 radioButton.setChecked(true)。
      【解决方案4】:

      这应该可行,

      int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
      

      【讨论】:

      • 如果在 Fragment 中使用,请使用 getActivity().findViewById()。
      【解决方案5】:

      你可以使用:

      RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
      

      【讨论】:

        【解决方案6】:

        //用于获取选中项的id

        int selectedID = myRadioGroup.getCheckedRadioButtonId();
        

        //获取选中项的视图

        View selectedView = (View)findViewById( selectedID);
        

        【讨论】:

          【解决方案7】:
           int index_selected = radio_grp.indexOfChild(radio_grp
                          .findViewById(radio_grp.getCheckedRadioButtonId()));
          

          【讨论】:

            【解决方案8】:

            试试这个

                    RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
                    group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup radioGroup, int i) {
                            View radioButton = radioGroup.findViewById(i);
                            int index = radioGroup.indexOfChild(radioButton);
                        }
                    });
            

            【讨论】:

            • 这行得通!但我不明白为什么我们需要使用这个“radioButton”视图..
            【解决方案9】:

            你可以的

            findViewById
            

            来自广播组。

            这里是示例:

            ((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
            

            【讨论】:

              【解决方案10】:

              以这种方式对我来说非常有效:

                  RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
                  int radioButtonID = radioGroup.getCheckedRadioButtonId();
                  RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
                  String selectedtext = (String) radioButton.getText();
              

              【讨论】:

                【解决方案11】:

                您只需先为 RadioButton 设置值,例如:

                RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
                radioButton.setId(1);        //some int value
                

                然后,只要选择这种间距的radiobutton,您就可以通过您给出的ID拉动它的值

                RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
                int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                                       //should be inside the "radioGroup"
                                                                       //in the XML
                

                干杯!

                【讨论】:

                  【解决方案12】:

                  就用这个吧:

                      int index = 2;
                      boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();
                  

                  【讨论】:

                    【解决方案13】:
                    radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);
                    
                      btnDisplay=(Button)findViewById(R.id.button);
                    
                      btnDisplay.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                            int selectedId=radioSexGroup.getCheckedRadioButtonId();
                            radioSexButton=(RadioButton)findViewById(selectedId);
                            Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
                         }
                      });
                    

                    【讨论】:

                      【解决方案14】:

                      你可以简单

                      -在onCreate方法中声明单选组和单选按钮

                      private RadioGroup GrupName;
                      private RadioButton NameButton;
                      

                      -在onCreate方法中设置视图id

                      GrupName = (RadioGroup) findViewById(R.id.radioGroupid);
                      

                      -获取使用选择的单选按钮 id

                      int id = GroupName.getCheckedRadioButtonId();
                      

                      -使用id来匹配buttonselected view

                      NameButton = (RadioButton) findViewById(id);
                      

                      -最终得到单选按钮的值

                      String valueExpected = NameButton.getText().toString();
                      

                      --- PS:如果你想要一个 INT 值,那么你可以投射它

                      int valueExpectedIn = Integer.parseInt(valueExpected);
                      

                      【讨论】:

                        【解决方案15】:

                        科特林:

                        val selectedIndex = radioButtonGroup?.indexOfChild(
                          radioButtonGroup?.findViewById(
                            radioButtonGroup.getCheckedRadioButtonId())
                        )
                        

                        【讨论】:

                          【解决方案16】:

                          这是一个 Kotlin 扩展,即使您的组包含 TextView 或任何非 RadioButton,也能获得 正确的位置

                          fun RadioGroup.getCheckedRadioButtonPosition(): Int {
                              val radioButtonId = checkedRadioButtonId
                              return children.filter { it is RadioButton }
                                  .mapIndexed { index: Int, view: View ->
                                      index to view
                                  }.firstOrNull {
                                      it.second.id == radioButtonId
                                  }?.first ?: -1
                          }
                          

                          【讨论】:

                            【解决方案17】:
                            radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
                            btnDisplay = (Button) findViewById(R.id.btnDisplay);
                            btnDisplay.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        // get selected radio button from radioGroup
                                        int selectedId = radioSexGroup.getCheckedRadioButtonId();
                                        // find the radiobutton by returned id
                                        radioSexButton = (RadioButton) findViewById(selectedId);
                            Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
                                    }
                                });
                            

                            【讨论】:

                              【解决方案18】:

                              迟到了,但这里是@Tarek360 的 Kotlin 答案的简化版,适合可能包含非 RadioButtons 的 RadioGroups:

                                  val RadioGroup.checkedIndex: Int
                                      get() = children
                                          .filter { it is RadioButton }
                                          .indexOfFirst { it.id == checkedRadioButtonId }
                              

                              如果你是RadioFroup 肯定只有RadioButtons 那么这可以很简单:

                                  private val RadioGroup.checkedIndex = 
                                      children.indexOfFirst { it.id == checkedRadioButtonId }
                              

                              那么你就没有findViewById的开销了。

                              【讨论】:

                              • 我在 9 年前发布了这个问题,但答案仍在不断涌现。有我的支持 :)
                              【解决方案19】:

                              您已经为每个单选按钮分配了一个 ID。使用 case 块,您可以手动检测选定的单选按钮,也可以使用 OnCheckedChangeListener 来检测。

                              xml:

                                  <RadioGroup
                                      android:id="@+id/rd_group_pick_reason"
                                      android:layout_width="0dp"
                                      android:layout_height="wrap_content"
                                      app:layout_constraintStart_toStartOf="parent"
                                      app:layout_constraintEnd_toEndOf="parent"
                                      app:layout_constraintTop_toBottomOf="@id/ti_titel"
                                      android:orientation="horizontal"
                                      android:paddingHorizontal="16dp"
                                      >
                                      <com.google.android.material.radiobutton.MaterialRadioButton
                                          android:id="@+id/rd_not_deliverable"
                                          android:layout_width="wrap_content"
                                          android:layout_height="wrap_content"
                                          android:layout_weight="0.5"
                                          android:text="@string/txt_not_deliverable"
                                          android:checked="true"
                                          />
                              
                                      <com.google.android.material.radiobutton.MaterialRadioButton
                                          android:id="@+id/rd_after_pack"
                                          android:layout_width="wrap_content"
                                          android:layout_height="wrap_content"
                                          android:layout_weight="0.5"
                                          android:text="@string/txt_after_pack"
                                          />
                                  </RadioGroup>
                              

                              java:

                              final RadioGroup radioGroup = dialogView.findViewById(R.id.rd_group_pick_reason);    
                              switch (radioGroup.getCheckedRadioButtonId()) {
                                  case R.id.rd_not_deliverable:
                                      // TODO
                                  break;
                                  case R.id.rd_after_pack:
                                      // TODO
                                  break;
                              }
                              

                              radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
                                  switch (group.getCheckedRadioButtonId()) {
                                      case R.id.rd_not_deliverable:
                                          System.out.println("not deliverable");
                                          break;
                                      case R.id.rd_after_pack:
                                          System.out.println("after pack");
                                          break;
                                  }
                              

                              【讨论】:

                                猜你喜欢
                                • 2016-08-14
                                • 1970-01-01
                                • 2012-04-08
                                • 2021-03-02
                                • 1970-01-01
                                • 1970-01-01
                                • 2020-08-13
                                • 1970-01-01
                                • 2018-06-13
                                相关资源
                                最近更新 更多