【问题标题】:How to check which radio button of a radio group is selected? [ANDROID]如何检查选择了单选组的哪个单选按钮? [安卓]
【发布时间】:2021-11-18 08:08:54
【问题描述】:

我正在使用具有多个单选按钮的两个单选组,我想检查选择了哪个单选按钮,以便我可以相应地调用特定功能。我正在使用 getCheckedRadioButtonId 方法来执行此操作,但它会引发空指针异常。如何以正确的方式做到这一点?我也尝试过其他方法。 任何帮助将不胜感激。 这是我的代码

public class MainActivity extends AppCompatActivity {
private EditText et_name;
private EditText et_age;
private EditText et_contactno;

private RadioGroup radioGroup_gender;
private RadioButton radioButton_male;
private RadioButton radioButton_female;
private RadioGroup radioGroup_methods;
private RadioGroup radioGroup_intent_methods;
private RadioButton radioButton_textfile;
private RadioButton radioButton_sharefpref;
private RadioButton radioButton_database;
private RadioButton radioButton_staticfields;
private RadioButton radioButton_intents;
private RadioButton radioButton_direct;
private RadioButton radioButton_bundle;
private RadioButton radioButton_parcelable;

private String name;
private String age;
private String contact_no;
private String gender;

private int gender_selected_id;
private int transfer_method_selected_id;
private int selected_intent_method_id;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    findViewsByIds();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "FAB CLICKED", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            executeSelectedMethod();
        }
    });
}

private void findViewsByIds() {
    et_name = (EditText) findViewById(R.id.et_name);
    et_age = (EditText) findViewById(R.id.et_age);
    et_contactno = (EditText) findViewById(R.id.et_contactno);
    radioGroup_gender = (RadioGroup) findViewById(R.id.rg_gender);
    radioButton_male = (RadioButton) findViewById(R.id.rb_male);
    radioButton_female = (RadioButton) findViewById(R.id.rb_female);

    radioGroup_methods = (RadioGroup) findViewById(R.id.rg_methods);
    radioGroup_intent_methods = (RadioGroup) findViewById(R.id.rg_intentmethods);
    radioButton_textfile = (RadioButton) findViewById(R.id.rb_textfile);
    radioButton_sharefpref = (RadioButton) findViewById(R.id.rb_sharefpref);
    radioButton_database = (RadioButton) findViewById(R.id.rb_database);
    radioButton_staticfields = (RadioButton) findViewById(R.id.rb_static);
    radioButton_intents = (RadioButton) findViewById(R.id.rb_intent);
    radioButton_direct = (RadioButton) findViewById(R.id.rb_intent_direct);
    radioButton_bundle = (RadioButton) findViewById(R.id.rb_intent_bundle);
    radioButton_parcelable = (RadioButton) findViewById(R.id.rb_intent_parcelable);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void executeSelectedMethod() {
    try {
        name = et_name.getText().toString();
        age = et_age.getText().toString();
        contact_no = et_contactno.getText().toString();
        RadioButton rb = (RadioButton) findViewById(radioGroup_gender.getCheckedRadioButtonId());
        String selectedgender = rb.getText().toString();
        if (selectedgender.equalsIgnoreCase("Male")) {
            gender = radioButton_male.getText().toString();
        } else if (selectedgender.equalsIgnoreCase("Female")) {
            gender = radioButton_female.getText().toString();
        }
        RadioButton rb_selected_method = (RadioButton) findViewById(radioGroup_gender.getCheckedRadioButtonId());
        String selectedRadioButtontext = rb_selected_method.getText().toString();
        if (selectedRadioButtontext.equalsIgnoreCase("Text File")) {
            ConstantFile.TRANSFER_METHOD = radioButton_textfile.getText().toString();
            executeTextFileMethod();
        } else if (transfer_method_selected_id == R.id.rb_sharefpref) {
            ConstantFile.TRANSFER_METHOD = radioButton_sharefpref.getText().toString();
        } else if (transfer_method_selected_id == R.id.rb_database) {
            ConstantFile.TRANSFER_METHOD = radioButton_database.getText().toString();
        } else if (transfer_method_selected_id == R.id.rb_static) {
            ConstantFile.TRANSFER_METHOD = radioButton_staticfields.getText().toString();
        } else {

            selected_intent_method_id = radioGroup_intent_methods.getCheckedRadioButtonId();
            if (selected_intent_method_id == R.id.rb_intent_direct) {
                ConstantFile.TRANSFER_METHOD = radioButton_direct.getText().toString();
            } else if (selected_intent_method_id == R.id.rb_intent_bundle) {
                ConstantFile.TRANSFER_METHOD = radioButton_bundle.getText().toString();

            } else if (selected_intent_method_id == R.id.rb_intent_parcelable) {
                ConstantFile.TRANSFER_METHOD = radioButton_parcelable.getText().toString();

            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void executeTextFileMethod() throws IOException {
    File transfer_file = new File("/sdcard/" + name + ".txt");
    transfer_file.createNewFile();
    FileOutputStream fileoutputstrem = new FileOutputStream(transfer_file);
    OutputStreamWriter outstreamwriter = new OutputStreamWriter(fileoutputstrem);
    outstreamwriter.append(name + ":" + age + ":" + contact_no + ":" + gender);
    fileoutputstrem.close();
    outstreamwriter.close();
    Toast.makeText(this, "This is my Toast message!",
            Toast.LENGTH_LONG).show();
    ConstantFile.TXTFILENAME = transfer_file.getName();
    goToNextActivity();
}

private void goToNextActivity() {
    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
    startActivity(intent);
}}

这是个例外:

Process: com.phaseone_datatransferbetweenactivities, PID: 22385
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.phaseone_datatransferbetweenactivities.MainActivity.executeSelectedMethod(MainActivity.java:118)
at com.phaseone_datatransferbetweenactivities.MainActivity.access$000(MainActivity.java:23)
at com.phaseone_datatransferbetweenactivities.MainActivity$1.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

【问题讨论】:

  • 你可以在单选组上 setOnCheckedChangeListener() 然后你会得到一个选中的单选按钮 id
  • 我认为您应该在组中创建一个具有默认选中状态的单选按钮。例如,使用性别按钮,应检查男性或女性。那么当你调用 radioGroup_gender.getCheckedRadioButtonId() 时,它总是会返回 id。如果没有检查,则返回 null

标签: android radio-button radio-group


【解决方案1】:

这是完美的工作:

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

int radioButtonID = radioGroup.getCheckedRadioButtonId();

RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);

String selectedText = (String) radioButton.getText();

【讨论】:

    【解决方案2】:

    尝试使用这个它也对我有用

    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(RadioGroup rGroup, int checkedId) {
    
                    int radioBtnID = rGroup.getCheckedRadioButtonId();
    
                    View radioB = rGroup.findViewById(radioBtnID);
    
                    int position = group.indexOfChild(radioB);
                }
            });
    

    【讨论】:

      【解决方案3】:

      试试这个,为我工作以获取 id 和 text 两者

      radioGroup = findViewById(R.id.radio_group);
          radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      
              @Override
              public void onCheckedChanged(RadioGroup rGroup, int checkedId) {
                  int radioButtonID = radioGroup.getCheckedRadioButtonId();
                  View radioButton = radioGroup.findViewById(radioButtonID);
                  int idx = radioGroup.indexOfChild(radioButton);
                  RadioButton r = (RadioButton) radioGroup.getChildAt(idx);
                  String selectedText = r.getText().toString();
                  System.out.println(idx);//For print Id
                  System.out.println(selectedText);//For print Text
              }
          });
      

      【讨论】:

        【解决方案4】:

        使用以下代码。

        RadioGroup rg = your_radio_group;
        
        // It will return currently selected radio button id from RadioGroup
        int id = rg.getCheckedRadioButtonId();
        
        if(id == your_one_radio_button_id){
         // First radio button is selected.
        } else if(id == your_two_radio_button_id){
         // Second radio button is selected.
        }
        

        【讨论】:

        • 我已经使用过了,它不会返回那个单选按钮的 id,而是返回类似“345323”的值
        • 检查过if条件结果吗?并且您需要为多个单选按钮添加 if else if。检查更新的答案
        • @user:我认为你得到的是像 R.id.yourid 这样的内部表示
        【解决方案5】:
         int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
        
         View radioButton = radioButtonGroup.findViewById(radioButtonID);
        
         int idx = radioButtonGroup.indexOfChild(radioButton);
        

        如果 RadioGroup 包含其他视图(如 TextView 等),则 indexOfChild() 方法将返回错误的索引。 在 RadioGroup 上获取选定的 RadioButton 文本

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

        【讨论】:

          【解决方案6】:
                          int id = radioGroup.getCheckedRadioButtonId(); 
                           if(id!=-1){
                              int radioButtonID = radioGroup.getCheckedRadioButtonId();
                              RadioButton radioButton = 
                                  (RadioButton)radioGroup.findViewById(radioButtonID);
          
                              String selectedtext = (String) radioButton.getText();
                                Toast.makeText(ReportsAct.this, ""+selectedtext, 
                                 Toast.LENGTH_SHORT).show();
                          }
          

          【讨论】:

            【解决方案7】:
            radioGroup = view.findViewById(R.id.choices);
             try {
                   radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
                   {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            RadioButton radioButton = view.findViewById(checkedId);
                            //selected index
                            mctSelectedAnsIndex = checkedId;
                            Log.e("mctSelectedAnsIndex",mctSelectedAnsIndex+"-"+checkedId);
                            int j = radioGroup.getChildCount();
                           //changing background of all radio buttons in group
                            for (int i = 0; i < j; i++) {
             radioGroup.getChildAt(i).setBackgroundColor(getActivity().getApplicationContext().
             getResources().getColor(R.color.lgrey));
                            }
            
            //code for changing background of selected one                      
            
            radioButton.setBackgroundColor(getActivity().getApplicationContext().
            getResources().getColor(R.color.color2));
            
                            if (mctSelectedAnsIndex == correctAnsChoice){
                                rightAnswers++;
                            }else{
                                wrongAnswers++;
                            }
            
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            

            【讨论】:

              【解决方案8】:

              这对我有用 - 在 java 中,选择活动片段内单选组内的选中单选按钮。

              RadioGroup radioGroup = getActivity().findViewById(R.id.radioGroup);
              int checked = radioGroup.getCheckedRadioButtonId();
              

              【讨论】:

                猜你喜欢
                • 2012-04-17
                • 1970-01-01
                • 2022-09-22
                • 1970-01-01
                • 1970-01-01
                • 2011-07-12
                • 2022-12-30
                • 2021-10-21
                • 2014-04-09
                相关资源
                最近更新 更多