我有一个广播组,可以选择"is"、“否”和“也许”。我想要一个函数来返回用户选择的选项。
这是我的代码
<RadioGroup
android:id="@+id/answerRadioGroup"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="@+id/submitButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/myTextView"
app:layout_constraintVertical_bias="0.26">
<RadioButton
android:id="@+id/yesRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Yes" />
<RadioButton
android:id="@+id/noRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="No" />
<RadioButton
android:id="@+id/maybeRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Maybe" />
</RadioGroup>
这是我尝试使用的函数:
private String checkGuess(){
guessRadioGroup = (RadioGroup) findViewById(R.id.guessRadioGroup);
int selectedId = guessRadioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(selectedId);
String s = (String) radioButton.getText().toString();
return s;
}
当我将 String s = (String) radioButton.getText().toString();
替换为 String s = "Whatever"
时,此函数似乎可以工作>。问题似乎在于使用 getText()
方法。
这是我在 MainActivity.java 中用来显示文本的内容:
TextView tempTextView = (TextView) findViewById(R.id.tempTextView);
tempTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String abc = checkGuess();
tempTextView.setText("You chose: " + abc);
}
});
最佳答案
您应该为 radioButton 使用 CustomListener
radioButton.setOnCheckedChangeListener(new CustomListener());
class CustomListener implements CompoundButton.OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()){
case R.id.rd1:
break;
}
}
}
关于java - 从 radio 组获取和返回文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163972/