Android 如何将方法分配给单选按钮?
我在Android 如何将方法分配给单选按钮?,android,Android,我在活动x中有五个RadioButton小部件,在活动y中有五个方法。我想为每个RadioButton指定一个特定的方法,因此当用户在活动x中选择一个按钮时,活动y中的一个方法将被执行首先,我建议您进一步阅读,以确保您完全理解此代码的输出 您需要在布局文件中创建RadioGroup和RadioButton小部件 <RadioGroup android:layout_width="fill_parent" android:layout_height="90dp"
活动x
中有五个RadioButton
小部件,在活动y
中有五个方法。我想为每个RadioButton
指定一个特定的方法,因此当用户在活动x
中选择一个按钮时,活动y
中的一个方法将被执行首先,我建议您进一步阅读,以确保您完全理解此代码的输出
您需要在布局文件中创建RadioGroup和RadioButton小部件
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:layout_below="@+id/radioGroup"
android:layout_centerHorizontal="true" />
注意:如上面提供的第一个链接所示,上述代码对TutorialPoint具有总积分
现在,如果您想检查选择了哪个按钮并执行一些逻辑(如果选择了),那么您可以使用switch
语句和selectedId
,使用语法int-selectedId=RadioExGroup.getSelectedButtonId(),从RadioGroup
获取该语句代码>
因此,要查看逻辑的走向,新代码段将如下所示:
int selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
switch(selectedId) {
case R.id.radioButton:
//perform logic is first button selected
break;
case R.id.radiobutton2:
//perform logic is second button selected
break;
}
希望这有助于您理解RadioGroup
和RadioButton
对象
您还可以直接将侦听器应用于RadioGroup
,以获取RadioButton
的checkedd
,该按钮无需点击按钮即可选中,如上图所示
radioSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId) {
case R.id.radiobutton:
//method for first radio button goes here
break;
case R.id.radiobutton2:
//method for second radio button goes here
break;
}
}
});
radioSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId) {
case R.id.radiobutton:
//method for first radio button goes here
break;
case R.id.radiobutton2:
//method for second radio button goes here
break;
}
}
});