【问题标题】:Get the checked radio button获取选中的单选按钮
【发布时间】:2019-11-26 04:59:53
【问题描述】:

我想创建动态 RadioGroup(带有动态单选选项)。我正在使用以下代码。

我的问题是,我怎样才能通过单击“Check Answer”按钮获得选择的选项。如果无线电组是通过 XML 布局添加的,那么我可以通过它的 ID 获取,但在这种情况下我无法这样做。

代码如下:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button">
    </LinearLayout>

    <TextView
        android:id="@+id/answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/button"
        android:textColor="#008b00"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check Answer"
        app:layout_constraintBottom_toBottomOf="parent"
        android:onClick="checkAnswer"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity:

package com.example.quiz8;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private LinearLayout linearLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        RadioGroup radioGroup = new RadioGroup(this);
        RadioButton radioButton;

        final String[] title = {"Male", "Female", "Other", "Secret"};

        for (int i = 0; i < title.length; i++) {
            radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setText(title[i]);
            radioGroup.addView(radioButton);
        }

        linearLayout.addView(radioGroup);
    }

    public void checkAnswer(View view) {
        //get the answer here
        TextView answerText = (TextView) findViewById(R.id.answer);
        answerText.setText("You selected the option...");
    }
}

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以为RadioGroup 设置一个标签,以便能够轻松找到它。 标签 可以是任何Object。我们将在这里使用String,它在您调用findViewWithTag()ViewGroup 中必须是唯一的。然后在checkAnswer() 中,您通过其标签 检索RadioGroup,从而获得选中的RadioButton 的文本。

    private static final String RADIOGROUP_TAG = "radiogroup";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        RadioGroup radioGroup = new RadioGroup(this);
        radioGroup.setTag(RADIOGROUP_TAG);
    
        RadioButton radioButton;
    
        final String[] title = {"Male", "Female", "Other", "Secret"};
    
        for (int i = 0; i < title.length; i++) {
            radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setText(title[i]);
            radioGroup.addView(radioButton);
        }
    
        linearLayout.addView(radioGroup);
    }
    
    public void checkAnswer(View view) {
        //get the answer here
        RadioGroup radioGroup = linearLayout.findViewWithTag(RADIOGROUP_TAG);
        int checkedId = radioGroup.getCheckedRadioButtonId();
        RadioButton radioButton = radioGroup.findViewById(checkedId);
        String text = radioButton.getText().toString();
    
        TextView answerText = (TextView) findViewById(R.id.answer);
        answerText.setText("You selected the option..." + text);
    }
    

    另一种选择:您可以将String[] titleRadioGroup 作为Activity 中的字段。这是有道理的,因为您在不止一个地方需要它们。

    private final String[] title  = {"Male", "Female", "Other", "Secret"};
    private RadioGroup radioGroup;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        radioGroup = new RadioGroup(this);
    
        RadioButton radioButton;
    
        for (int i = 0; i < title.length; i++) {
            radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setText(title[i]);
            radioGroup.addView(radioButton);
        }
    
        linearLayout.addView(radioGroup);
    }
    
    public void checkAnswer(View view) {
        //get the answer here
        int checkedId = radioGroup.getCheckedRadioButtonId();
        TextView answerText = (TextView) findViewById(R.id.answer);
        // Note: make sure there is a checked RadioButton! 
        answerText.setText("You selected the option..." + title[checkedId]);
    }
    

    【讨论】:

      【解决方案2】:

      您可以简单地检查所选的。

      public class MainActivity extends AppCompatActivity {
      
          private LinearLayout linearLayout = null;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
              RadioGroup radioGroup = new RadioGroup(this);
              RadioButton radioButton;
      
              final String[] title = {"Male", "Female", "Other", "Secret"};
      
              for (int i = 0; i < title.length; i++) {
                  radioButton = new RadioButton(this);
                  radioButton.setId(i);
                  radioButton.setText(title[i]);
                  radioGroup.addView(radioButton);
                  radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                      @Override
                      public void onCheckedChanged(RadioGroup group, int checkedId) {
                      //checkedId is the RadioButton selected
                  }
      
              }
      
              linearLayout.addView(radioGroup);
          }
      
          public void checkAnswer(View view) {
              //get the answer here
              TextView answerText = (TextView) findViewById(R.id.answer);
              answerText.setText("You selected the option...");
          }
      }
      

      【讨论】:

      • 感谢您的回答。有没有办法通过单击检查答案按钮(即在 checkAnswer 函数中)获得检查答案?
      • 是的,你可以。只需声明一个 int 并在“onCheckedChanged”方法中为其赋值。例如 int i = 0; -> i = 已检查 ID;然后在“checkAnswer 查询该 int。这将为您提供当前选择的 id。希望对您有所帮助
      【解决方案3】:

      1) 您可以在OnClickListner() 中添加以下代码以检查是否单击了所需的复选框。

      // Is the button now checked?
      boolean checked = ((RadioButton) view).isChecked();
      
      // Check which radio button was clicked
      switch(view.getId()) {
          case R.id.radio_pirates:
              if (checked)
                  // Pirates are the best
              break;
          case R.id.radio_ninjas:
              if (checked)
                  // Ninjas rule
              break;
      }
      

      更多帮助可以在单选按钮文档中找到:Radio Button Documentation

      2) 另一种方法:更好的方法是使用RadioGroup 并在其上设置监听器以相应地更改和更新视图(节省您拥有 2 个或 3 个或 4 个等监听器)。

      RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
      radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
      {
          @Override
          public void onCheckedChanged(RadioGroup group, int checkedId) {
              // checkedId is the RadioButton selected
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 2013-09-28
        • 2021-12-29
        • 1970-01-01
        • 2016-11-09
        相关资源
        最近更新 更多