Java 如何获取单选按钮的 id 并转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23946337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get radio button's id and convert to string?
提问by juliet
I am working in Android Studio and am trying to get the ID of the selected radio button and then store the ID in a string. Is this possible?
我在 Android Studio 中工作并试图获取所选单选按钮的 ID,然后将该 ID 存储在一个字符串中。这可能吗?
I have tried replacing the .getText() method below with .getId() but it wont let me store it as a string:
我曾尝试用 .getId() 替换下面的 .getText() 方法,但它不会让我将其存储为字符串:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId);
String text = checkedRadioButton.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
采纳答案by drew moore
getId()returns an int- which, like all primitive types, does not have a toString()(or any other) method. This is because, while all Objects have a toString()method, primitives are not Objects - but lucky for you, Java provides wrapper classesthat areObjects for all primitive type. In the case of int, the corresponding wrapper class is called Integer:
getId()返回int- ,与所有原始类型一样,没有toString()(或任何其他)方法。这是因为,虽然所有的对象有一个toString()方法,原始数据不是对象-但幸运的你,Java提供包装类即是对所有原始类型的对象。在 的情况下int,调用相应的包装类Integer:
String text = (Integer)checkedRadioButton.getId().toString();
Here, we're explicitly casting the intreturned by getId()to an Integerobject, then calling toString()on that object.
在这里,我们将int返回的 by显式转换getId()为一个Integer对象,然后调用toString()该对象。
Alternatively, you can take advantage of autoboxingto let Java handle the "wrapping" for you automatically:
或者,您可以利用自动装箱让 Java 自动为您处理“包装”:
Integer id = checkedRadioButton.getId();
String text = id.toString();
Note that getId()is still returning an int, but because you declared the idvariable to be an Integer, Java "boxes" the return value to its wrapper class automatically - hence "autoboxing".
请注意,getId()它仍然返回 an int,但是因为您将id变量声明为 an Integer,Java 会自动将返回值“装箱”到其包装类中——因此是“自动装箱”。
You can also use the static Integer.toString()method:
您还可以使用静态Integer.toString()方法:
String text = Integer.toString(checkedRadioButton.getId())
but note that, under the hood, the same operations are being performed here.
但请注意,在幕后,这里正在执行相同的操作。
回答by Omar HossamEldin
beside @drewmore solution you can use also
除了@drewmore 解决方案,您还可以使用
String text = String.valueOf(checkedRadioButton.getId());
String text = String.valueOf(checkedRadioButton.getId());

