普通对话框

AlertDialog对话框_ide

public void click1(View v) {
    //这里不能用 getApplicationContext()方法来获取上下文
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("警告")
            .setMessage("世界上最遥远的距离是没有网!")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LogHelper.LogI("Good");
                }
            })
            .setNegativeButton("Bad", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LogHelper.LogI("Cancel");
                }
            })  
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LogHelper.LogI("Good!");
                }
            })
            .show();
}

单选按钮对话框

AlertDialog对话框_python_02

public void click2(View v) {
    //将要显示的单选项
    final String[] items = {"C#", "Python", "Java", "C++", "android.webkit.JavascriptInterface", "H5"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    //绑定单选项,checkedItem 如果是-1那么是没有选中项
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String selectedItem = items[which];
            Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //关闭对话框
            dialog.dismiss();
        }
    })
    .show();
}

多选对话框

AlertDialog对话框_python_03

public void click3(View v) {
    //将要显示的单选项
    final String[] items = {"C#", "Python", "Java", "C++", "JS", "H5"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
  	//如果第二个参数不为null 那么必须哟要传递一个相同数量的数组
    builder.setMultiChoiceItems(items, new boolean[]{true, true, false, false, false, false}, new 		DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if (isChecked) {
                Toast.makeText(getApplicationContext(), items[which], Toast.LENGTH_SHORT).show();
            }
        }
    }).show();
}

除非特殊声明否则,本博客文章均属 鲁迅认识的那只猹 原创,未经许可禁止转载,否则将保留追究法律责任的权利。

如果本博客损害了您的相关权益,请及时联系我,我将妥善处理。