单选按钮选择在Android上改变吐司 [英] Radio Button selection Changes Toast on Android
问题描述
我在写一个简单的测试应用程序。有应用程序中的两个单选按钮。有ID是radio_red和radio_blue。我想创造一个onClickListener事件读取相关的按钮上的文本,然后返回一个基本的正确或错误的面包。
I was writing a simple test application. There are two radio buttons within the app. There id's are "radio_red" and "radio_blue". I wanted to create an onClickListener event that read the text associated to the button and then returned a basic "Right" or "Wrong" toast.
这里是code的例子:
Here is a sample of the code:
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v){
RadioButton rb = (RadioButton) v;
String ans = rb.getText().toString();
String an1 = "";
if (ans.trim() == "Yes") {
ans = "That's Right.";
}
else if (ans.trim() == "No") {
ans = "thats wrong.";
}
else {
ans = "none.";
}
Toast.makeText(v.getContext(), ans , Toast.LENGTH_SHORT).show();
}
到目前为止,没有喜悦。这是我的code段。我检查了我的main.xml中和相关的按钮上的文本正确referneced。我加修剪,以确保这一点。然而,所有这一切都在不断敬酒返回是无。我在想什么?感谢您事先的任何帮助。
So far no joy. Here is my code snippet. I've checked my "main.xml" and the text associated to the buttons are referneced correctly. I added trim to make sure of that. However, all that is ever returned in the toast is "none." What am I missing? Thanks in advance for any help.
推荐答案
您要处理的<一个href="http://developer.android.com/intl/fr/reference/android/widget/RadioGroup.html"><$c$c>RadioGroup$c$c>,不是单选
。该 RadioGroup中
可以告诉你有关无线电管制,喜欢哪一个被选中的更多元的细节。例如,在你的听众,你应该使用<一个href="http://developer.android.com/intl/fr/reference/android/widget/RadioGroup.html#getCheckedRadioButtonId%28%29"><$c$c>RadioGroup.getCheckedRadioButtonId()$c$c>.
You want to deal with the RadioGroup
, not the RadioButton
. The RadioGroup
can tell you more meta-details about the radio controls, like which one is checked. For example, in your listener you should use RadioGroup.getCheckedRadioButtonId()
.
另外,你可以添加一个监听到RadioGroup中本身设置一个切换的背景下,使用<一个href="http://developer.android.com/intl/fr/reference/android/widget/RadioGroup.html#setOnCheckedChangeListener%28android.widget.RadioGroup.OnCheckedChangeListener%29"><$c$c>RadioGroup.setOnCheckedChangeListener()$c$c>.它告诉你哪个单选
是pressed的能力。
Alternatively, you could add a listener to the RadioGroup itself that sets a toggle in the background, using RadioGroup.setOnCheckedChangeListener()
. It has the capability of telling you which RadioButton
was pressed.
这篇关于单选按钮选择在Android上改变吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!