Android Studio 从单选按钮获取值,并在其他地方使用它



>我有下面的代码,使用单选按钮并获取值并将其作为函数的字符串返回。希望我可以在主程序的其他地方使用它。但是,事实并非如此。它将允许我使用变量btn,如果我通过向final string []声明来执行atl-enter建议,它将返回 null。大多数在线教程和堆栈溢出上一个问题仅包括从onCheckedChanged内选择的任何按钮中烘烤文本。

public String listeneronbutton() {
String btn;
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(checkedID);
Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
btn = String.valueOf(radioButton.getText());      //(error here: variable 'btn' is accessed from within inner class, needs to be declared final)
}
});
return btn;
}

如何正确获取函数listeneronbutton()能够获取和返回btn值?

像这样更改您的方法:

public String listeneronbutton() {
String btn;
RadioGroup radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(checkedID);
Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
btn = String.valueOf(radioButton.getText());      
return btn;
}

你不能有一个同时添加OnCheckedChangeListener和获取String的方法(因为职责分离和一种方法只应该运行一次,另一个方法更频繁(。 同样,您可以将方法instanceRadioGroup()添加到onCreate()onCreateView(),然后使用方法getButtonText()获取当前值。

此外,变量int checkedId已经被传递到作用域中,因此可以使用它。

/** the handle for the {@link RadioGroup} */
private RadioGroup mRadioGroup = null;
/** this field holds the button's text */
private String mButtonText = null;
/** the setter for the field */
protected void setButtonText(@Nullable String value) {
this.mButtonText = value;
}
/** the getter for the field */
protected String getButtonText() {
return this.mButtonText;
}
/** it sets mButtonText by checkedId */
protected void updateButtonText(int checkedId) {
if ((checkedId == -1)) {
this.setButtonText(null);
} else {
RadioButton radioButton = (RadioButton) this.mRadioGroup.findViewById(checkedId);
this.setButtonText(radioButton.getText());
}
}
/** this code should only run once, onCreate() or onCreateView() */
protected void instanceRadioGroup() {
/* setting the handle for the {@link RadioGroup} */
this.mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
/* update the field with the text of the default selection */
int checkedId = this.mRadioGroup.getCheckedRadioButtonId();
this.updateButtonText(checkedId);
/* and also add an onCheckedChange listener */
this.mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
updateButtonText(checkedId);
}
});
}

String btn声明为字段。因此,您可以在类内的任何地方访问。

public class Test{
String btn;
public String listeneronbutton(){
return btn;
}
}

最新更新