AlertDialog对话框

普通对话框

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();
}

单选按钮对话框

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();
}

多选对话框

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();
}
posted @ 2017-06-12 19:29  鲁迅认识的那只猹  阅读(384)  评论(0编辑  收藏  举报