帮我用android studio写一个程序,两个单选按钮,一个是男,一个是女 。当选中“男”,则“男”字背景变红,字体变白色;当选中“女”,则“女”字背景变红,字体变白色;
时间: 2024-02-22 14:01:48 浏览: 11
好的,首先在 XML 布局文件中添加两个单选按钮和一个 TextView,代码如下:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/male_rb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"/>
<RadioButton
android:id="@+id/female_rb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</LinearLayout>
<TextView
android:id="@+id/gender_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="您选择的性别是:"/>
```
接下来在 MainActivity 中为两个单选按钮设置 OnCheckedChangeListener,根据选择的结果改变 TextView 的文本和背景颜色,代码如下:
```java
public class MainActivity extends AppCompatActivity {
private RadioButton maleRb, femaleRb;
private TextView genderTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maleRb = findViewById(R.id.male_rb);
femaleRb = findViewById(R.id.female_rb);
genderTv = findViewById(R.id.gender_tv);
maleRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
genderTv.setText("您选择的性别是:男");
genderTv.setBackgroundColor(Color.RED);
genderTv.setTextColor(Color.WHITE);
}
}
});
femaleRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
genderTv.setText("您选择的性别是:女");
genderTv.setBackgroundColor(Color.RED);
genderTv.setTextColor(Color.WHITE);
}
}
});
}
}
```
这样就完成了程序的编写,当选中“男”时,TextView 的文本变为“您选择的性别是:男”,背景变为红色,字体变为白色;当选中“女”时,TextView 的文本变为“您选择的性别是:女”,背景变为红色,字体变为白色。