实现以下效果,当选择单选框1时,单选框上方显示【我选择的是radio1】,当选择单选框2时,单选框上方显示【我选择的是radio2】,要求写出布局文件代码和Activity代码
时间: 2024-03-01 16:49:58 浏览: 104
纯css3实现效果超级炫的checkbox复选框和radio单选框
布局文件代码(activity_main.xml):
```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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<RadioButton
android:id="@+id/radio_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio 1" />
<RadioButton
android:id="@+id/radio_button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio 2" />
</RadioGroup>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge" />
</LinearLayout>
```
Activity 代码(MainActivity.java):
```java
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radio_group);
radioButton1 = findViewById(R.id.radio_button_1);
radioButton2 = findViewById(R.id.radio_button_2);
textView = findViewById(R.id.text_view);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radio_button_1) {
textView.setText("我选择的是radio1");
} else if (checkedId == R.id.radio_button_2) {
textView.setText("我选择的是radio2");
}
}
});
}
}
```
阅读全文