安卓radiobutton控件代码
时间: 2024-09-26 11:01:59 浏览: 31
Android中的RadioButton是一种单选按钮组件,用户只能从一组选项中选择一个。以下是创建一个简单的RadioButton的基本步骤及代码示例:
```java
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class RadioButtonActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radiobutton);
// 初始化RadioGroup和RadioButton
radioGroup = findViewById(R.id.radio_group);
radioButton1 = findViewById(R.id.radioButton1); // 假设id为"radioButton1"
radioButton2 = findViewById(R.id.radioButton2); // 假设id为"radioButton2"
// 设置初始选中的RadioButton
radioButton1.setChecked(true);
// 创建一个Button并设置点击事件监听
Button selectButton = findViewById(R.id.select_button);
selectButton.setOnClickListener(view -> {
if (radioButton1.isChecked()) {
radioButton2.setChecked(false);
} else {
radioButton1.setChecked(true);
}
});
}
// 如果需要的话,可以添加RadioGroup的CheckedChangeListener监听广播组的状态变化
@Override
protected void onResume() {
super.onResume();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton1:
Toast.makeText(RadioButtonActivity.this, "RadioButton 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
Toast.makeText(RadioButtonActivity.this, "RadioButton 2 selected", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
```
在这个例子中,我们首先设置了第一个RadioButton为默认选中状态,然后当用户点击按钮时会切换选中状态。`RadioGroup`的`OnCheckedChangeListener`会在用户切换选项时触发回调。
阅读全文