android 两个RADIOBUTTON的代码 并触发事件
时间: 2024-01-07 11:05:54 浏览: 33
以下是一个示例代码,其中有两个RadioButton,并且使用了RadioGroup来将它们组合在一起,以便可以触发事件:
```java
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton1, radioButton2;
@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);
// 设置初始选中状态
radioButton1.setChecked(true);
// 设置选项卡切换监听器
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio_button_1:
// RadioButton 1 被选中
Toast.makeText(MainActivity.this, "RadioButton 1 被选中", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_button_2:
// RadioButton 2 被选中
Toast.makeText(MainActivity.this, "RadioButton 2 被选中", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
```
在这段代码中,我们首先找到了RadioGroup和两个RadioButton,并将它们存储在变量中以便于之后的使用。然后,我们设置了初始选中状态(这里设置了RadioButton 1为初始选中状态),并添加了一个OnCheckedChangeListener,以便在选项卡切换时触发事件。在OnCheckedChangeListener中,我们使用switch语句来检查哪个RadioButton被选中,并根据选中的RadioButton显示一个Toast消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)