Androidx学习笔记(25)-- 单选对话框

单选对话框

    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("选择你的性别");
  • 定义单选选项
  • final String[] items = new String[]{
            "男", "女", "其他"
    };
    //-1表示没有默认选择
    //点击侦听的导包要注意别导错  -1代表默认没有选中
    builder.setSingleChoiceItems(items, -1, new OnClickListener() {
    
        //which表示点击的是哪一个选项
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "您选择了" + items[which], 0).show();
            //对话框消失
            dialog.dismiss();
        }
    });
    
    builder.show();

案例代码

public void click2(View v){
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("请选择性别");
		final String[] items = new String[]{
				"男",
				"女"
		};
		
		builder.setSingleChoiceItems(items, -1, new OnClickListener() {
			
			//which:用户所选的条目的下标
			//dialog:触发这个方法的对话框
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this, "您选择的是:" + items[which], 0).show();
				//关闭对话框
				dialog.dismiss();
			}
		});
		builder.show();
	}



你可能感兴趣的:(Android应用)