►Button which 值
PositiveButton : -1, 左鍵
NegativeButton : -2, 右鍵
NeutralButton : -3, 中間鍵
► 提示
NegativeButton : -2, 右鍵
NeutralButton : -3, 中間鍵
►加入 Viewnew AlertDialog.Builder(Main.this) .setTitle("提示") //.setIcon(android.R.drawable.btn_star);//指定圖示 .setMessage("確定退出嗎?") .setPositiveButton("OK", ok) //.setNeutralButton("btn3", listener); .setNegativeButton("Cancel", cancel).show()
►複選EditText et = new EditText(Main.this); // new AlertDialog.Builder(Main.this).setTitle("加入View") .setIcon(android.R.drawable.ic_dialog_info) .setView(et) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(Main.this, et.getText().toString(), 2000).show(); dialog.dismiss(); } }) .setNegativeButton("Cancel", null).show();
►單選String[] items = new String[] { "Item1", "Item2", "Item3", "Item4" }; boolean[] itemsChecked = new boolean[items.length]; //ArrayList<Integer> selList= new ArrayList<Integer>(); new AlertDialog.Builder(Main.this).setTitle("複選") .setMultiChoiceItems(items, null,//選項初值 new boolean[] { false, false, false, false } new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { itemsChecked[which] = isChecked; /*if(isChecked) selList.add(which); else if (selList.contains(which)) selList.remove(Integer.valueOf(which));*/ } }) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String result = "select: "; for(int i=0; i< itemsChecked.length; i++) if (itemsChecked[i]) { result += items[i]+","; itemsChecked[i] = false; } /*for(int i=0; i< selList.size()-1; i++) result += selList.get(i)+","; selList.clean();*/ Toast.makeText(Main.this, result, 2000).show(); dialog.dismiss(); } }) .setNegativeButton("Cancel", cancel).show();
►列表new AlertDialog.Builder(Main.this).setTitle("單選") .setSingleChoiceItems(new String[] { "Item1", "Item2", "Item3" }, 0, ok) .setNegativeButton("Cancel", cancel).show();
►ClickListenernew AlertDialog.Builder(Main.this) .setTitle("列表") .setItems( new String[] { "Item1", "Item2" }, ok) .setNegativeButton("OK", cancel).show();
DialogInterface.OnClickListener cancel = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }; DialogInterface.OnClickListener ok = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.d("dd","which="+which); dialog.dismiss(); } };