我下面有简单的代码,我不明白为什么它对我不起作用。我只想做的就是根据我单击的单选按钮来显示(吐司)“男”或“女”。
这是主要活动的代码:
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();
}
}
);
}
和广播组:
<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>
有人可以指出我所缺少的吗?这真令人沮丧。
您的代码必须如下所示:
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();
}
试试这个,我尝试一下很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句