编写程序,利用RadioGroup组件实现性别的单向选择,分别给出MainActivity.java和activity_main.xml中的代码
时间: 2023-04-05 09:03:22 浏览: 126
以下是 MainActivity.java 的代码:
```
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RadioGroup mRadioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadioGroup = findViewById(R.id.radio_group_gender);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio_button_male:
Toast.makeText(MainActivity.this, "您选择了男性", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_button_female:
Toast.makeText(MainActivity.this, "您选择了女性", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
```
以下是 activity_main.xml 的代码:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="@+id/radio_group_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radio_button_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男性" />
<RadioButton
android:id="@+id/radio_button_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女性" />
</RadioGroup>
</LinearLayout>
```
阅读全文