绑定对话框和选项按钮
功能说明:
- 单选对话框:点击选择按钮,跳出单选对话框,单选对话框被点击后,单选按钮状态随之改变。
- 多选对话框:点击选择按钮,跳出多选对话框,对话框被点击后,多选框状态随之改变。
效果图:
- 点击前
点击后
代码实现(MainActivity部分)
public class RegiActivity<setT, dialog> extends AppCompatActivity {
private Button myBtn_one;//注册按钮
private Button myBtn_sex;//性别选择矩形按钮
private Button myBtn_hobby;//爱好选择按钮
private RadioGroup myRadio;//性别选择圆形按钮
//文本输入控件
private EditText rt_name;
private EditText rt_password;
private EditText rt_sclass;
private EditText rt_sgrade;
//多选对话框选项
private CheckBox singbox;
private CheckBox musicbox;
private CheckBox readbox;
private CheckBox swimbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regi);
myBtn_one=findViewById(R.id.btn_one);//绑定按钮
myRadio=findViewById(R.id.rdg);
rt_name=findViewById(R.id.name);
rt_password=findViewById(R.id.password);
rt_sclass=findViewById(R.id.sclass);
rt_sgrade=findViewById(R.id.sgrade);
musicbox = findViewById(R.id.musicbox);
readbox=findViewById(R.id.readbox);
singbox=findViewById(R.id.singbox);
swimbox=findViewById(R.id.swimbox);
//性别对话框------单选框
myBtn_sex=findViewById(R.id.btn_sex);
myBtn_sex.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog;
final String[] sex={"男", "女"};//final
dialog=new AlertDialog.Builder(RegiActivity.this).setTitle("请选择性别").setSingleChoiceItems(sex,
0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {//默认选择性别:男,点击选择性别女时改变单选按钮状态
switch (which) {
case 0:
Toast.makeText(RegiActivity.this,"你选择的性别是:"+sex[0],Toast.LENGTH_SHORT).show();
myRadio.check(R.id.boy);
case 1:
Toast.makeText(RegiActivity.this,"你选择的性别是:"+sex[1],Toast.LENGTH_SHORT).show();
myRadio.check(R.id.girl);
}
}
}).setPositiveButton("确定",null).show();
}
});
//爱好对话框
myBtn_hobby=findViewById(R.id.btn_hobby);
myBtn_hobby.setOnClickListener(new View.OnClickListener() {//通过获取点击对话框选项的下标,设置对应复选框状态为选中
@Override
public void onClick(View v) {
final String[] hobby = {"游泳", "唱歌", "音乐", "读书"};
final boolean[] items = {false, false, false, false};
AlertDialog dialog = new AlertDialog.Builder(RegiActivity.this).setTitle("请选择兴趣爱好").setMultiChoiceItems(hobby, items,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
items[which] = isChecked;
switch (which) {
case 0:
swimbox.setChecked(true);
case 1:
singbox.setChecked(true);
case 2:
musicbox.setChecked(true);
case 3:
readbox.setChecked(true);
}
}
}).show();
}
});
myBtn_one.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//Date();
}
});
}
}
原本想通过传递参数来改变按钮的状态的,奈何自己太菜!不过直接设置也比较好用。