Android从选定的单选按钮获取价值
Posted
技术标签:
【中文标题】Android从选定的单选按钮获取价值【英文标题】:Android getting value from selected radiobutton 【发布时间】:2013-08-13 07:12:20 【问题描述】:我有一段代码,在 RadioGroup
中包含三个 RadioButton
s。我想设置一个onCheckedListener
,它将在Toast
中显示RadioButton
的值。但是,到目前为止我所得到的并没有奏效。如何获取RadioButton
的值并将其显示在Toast
中?这是我的代码:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
final String value =
((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
.getText().toString();
rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
public void onCheckedChanged(RadioGroup group, int checkedId)
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
);
XML 文件:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="152dp" >
<RadioButton
android:id="@+id/radio0"
android:layout_
android:layout_
android:text="Choose 1" />
<RadioButton
android:id="@+id/radio1"
android:layout_
android:layout_
android:text="Choose 2" />
<RadioButton
android:id="@+id/radio2"
android:layout_
android:layout_
android:text="Choose 3" />
</RadioGroup>
</RelativeLayout>
【问题讨论】:
【参考方案1】:经过测试和工作。检查this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
public void addListenerOnButton()
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener()
@Override
public void onClick(View v)
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
);
xml
<RadioGroup
android:id="@+id/radio"
android:layout_
android:layout_ >
<RadioButton
android:id="@+id/radioMale"
android:layout_
android:layout_
android:text="@string/radio_male"
android:checked="true" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_
android:layout_
android:text="@string/radio_female" />
</RadioGroup>
【讨论】:
这是您从 mykong 链接中看到的内容...而不是使用按钮,我们如何获取选定的 id..用于多个无线电组。 完美!!!回答...很容易获得单选按钮视图,当用户单击时!【参考方案2】:如果您想在选择其中一个单选按钮上做一些工作(没有任何额外的确定按钮或其他东西),您的代码很好,更新很少。
public class MainActivity extends Activity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
public void onCheckedChanged(RadioGroup group, int checkedId)
switch(checkedId)
case R.id.radio0:
// do operations specific to this selection
break;
case R.id.radio1:
// do operations specific to this selection
break;
case R.id.radio2:
// do operations specific to this selection
break;
);
【讨论】:
只是一个小的更正,一个非常小的更正,你已经两次声明了'rg'。它根本不会产生影响,只是使代码更具可读性。【参考方案3】:radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
);
【讨论】:
【参考方案4】:int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();
希望这可行。您可以通过上述方式将输出转换为字符串。
gender.getCheckedRadioButtonId();
- 性别是 RadioGroup 的 id。
【讨论】:
工作正常!但是当我将数据保存到 firebase 并且如果我错过任何 Radio btn 来检查应用程序崩溃时“尝试在空对象引用上调用虚拟方法'java.lang.CharSequence android.widget.RadioButton.getText()'”任何解决方案【参考方案5】:mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId)
RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
);
【讨论】:
【参考方案6】:对于以编程方式填充并希望获取索引的任何人,您可能会注意到,当您返回活动/片段并重新添加这些单选按钮时,checkedId 会发生变化。解决这个问题的一种方法是使用索引设置标签:
for(int i = 0; i < myNames.length; i++)
rB = new RadioButton(getContext());
rB.setText(myNames[i]);
rB.setTag(i);
myRadioGroup.addView(rB,i);
然后在你的听众中:
myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
int mySelectedIndex = (int) radioButton.getTag();
);
【讨论】:
【参考方案7】:只需使用getCheckedRadioButtonId()
函数来判断是否有任何检查,如果-1
是return
值,则可以避免显示吐司
【讨论】:
【参考方案8】:Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId)
RadioButton rb= (RadioButton) findViewById(checkedId);
team = rb.getText().toString();
);
【讨论】:
【参考方案9】:XML 中的 RadioGroup
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_ android:layout_>
<RadioGroup
android:layout_
android:layout_
android:orientation="vertical">
<RadioButton
android:layout_
android:layout_
android:text="Java"/>
</RadioGroup>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_ android:layout_>
<TextView
android:layout_
android:layout_
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="@+id/txtView"/>
<RadioGroup
android:layout_
android:layout_
android:orientation="vertical"
android:id="@+id/rdGroup"
android:layout_below="@+id/txtView">
<RadioButton
android:id="@+id/rdbJava"
android:layout_
android:layout_
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbPython"
android:layout_
android:layout_
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAndroid"
android:layout_
android:layout_
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAngular"
android:layout_
android:layout_
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="@+id/getBtn"
android:layout_
android:layout_
android:layout_marginLeft="100dp"
android:layout_below="@+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
RadioButton android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
);
public void onRadioButtonClicked(View view)
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId())
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
【讨论】:
【参考方案10】:非常感谢克里斯。
这是我的解决方案:
RadioGroup radgroup_opcionesEventos = null;
private static String[] arrayEventos =
"Congestión", "Derrumbe", "Accidente"
;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
int i=0;//a.new.ln
for(String evento : arrayEventos)
//RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
radgroup_opcionesEventos.addView(nuevoRadio,i);
RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
primerRadio.setChecked(true);
private RadioButton crearRadioButton(String evento, int n)
//RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln
LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
nuevoRadio.setLayoutParams(params);
nuevoRadio.setText(evento);
nuevoRadio.setTag(evento);
return nuevoRadio;
@Override
protected void onResume()
radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
//int mySelectedIndex = (int) radioButton.getTag();
String mySelectedIndex = radioButton.getTag().toString();
);
super.onResume();
【讨论】:
【参考方案11】:当 RadioButtons 是动态生成时,我在获取单选按钮 ID 时也遇到了问题。如果您尝试使用RadioButton.setId()
手动设置 ID,它似乎不起作用。对我有用的是使用View.getChildAt()
和View.getParent()
来遍历单选按钮并确定选中了哪一个。您只需要首先通过findViewById(R.id.myRadioGroup)
获取 RadioGroup,然后遍历它的子项。当您遍历您所在的按钮时,您会知道,您可以简单地使用RadioButton.isChecked()
来确定该按钮是否被选中。
【讨论】:
如果您查看 chinna 的答案,该页面已链接 @AbrahamUribe 您能否查看我编辑的答案,看看它是否比之前被标记的答案更好? @mikeTheLiar 你是对的,我没有注意到原始答案中的链接,那是我的错误。 对于这种情况,我认为更好的解决方案是使用 setTag(i),其中 i 是您用于填充无线电组的数组的索引。我添加了一个答案来展示这种方式。以上是关于Android从选定的单选按钮获取价值的主要内容,如果未能解决你的问题,请参考以下文章