Android – cannot display the value of a button in a radio button group
•
Android
I have a simple code below. I don't understand why it doesn't work for me. All I want to do is display (toast) "male" or "female" according to the radio button I click
This is the code of the main activity:
private static RadioGroup radio_g;
private static RadioButton radio_b;
private static Button button_sbm;
public void onClickListenerButton() {
radio_g = (RadioGroup)findViewById(R.id.genderButton);
button_sbm = (Button)findViewById(R.id.getBMI);
button_sbm.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected_id = radio_g.getCheckedRadioButtonId();
radio_b = (RadioButton)findViewById(selected_id);
Toast.makeText(MainActivity.this,
radio_b.getText().toString(),Toast.LENGTH_SHORT ).show();
}
}
);
}
And broadcast groups:
<RadioGroup
android:id="@+id/genderButton"
android:layout_width="124dp"
android:layout_height="67dp"
android:layout_marginLeft="89dp"
android:layout_marginStart="88dp"
android:layout_marginTop="63dp"
android:visibility="visible"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ageField"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1">
<RadioButton
android:id="@+id/maleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="false"
android:text="Male"
tools:text="male" />
<RadioButton
android:id="@+id/femaleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Female"
tools:text="female" />
</RadioGroup>
Can anyone point out what I lack? This is really frustrating
resolvent:
Your code must look like this:
public class FormActivity extends Activity implements View.OnClickListener {
private static RadioGroup radio_g;
private static RadioButton radio_b;
private static Button button_sbm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
// initialize component here like this
radio_g = (RadioGroup)findViewById(R.id.genderButton);
button_sbm = (Button)findViewById(R.id.getBMI);
// Then call listener on button click like this
button_sbm .setOnClickListener(this);
}
@Override
public void onClick(View v) {
int selected_id = radio_g.getCheckedRadioButtonId();
radio_b = (RadioButton)findViewById(selected_id);
Toast.makeText(MainActivity.this,
radio_b.getText().toString(),Toast.LENGTH_SHORT ).show();
}
Try this. I'll try it. It's good
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码