AlertDialog 用法

1 篇文章 / 0 new
author
AlertDialog 用法
►Button which 值
PositiveButton : -1, 左鍵
NegativeButton : -2, 右鍵
NeutralButton : -3, 中間鍵
► 提示
new AlertDialog.Builder(Main.this)
.setTitle("提示")
//.setIcon(android.R.drawable.btn_star);//指定圖示
.setMessage("確定退出嗎?")
.setPositiveButton("OK", ok)
//.setNeutralButton("btn3", listener);
.setNegativeButton("Cancel", cancel).show()
►加入 View
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();
►列表
new AlertDialog.Builder(Main.this)
.setTitle("列表")
.setItems( new String[] { "Item1", "Item2" }, ok)
.setNegativeButton("OK", cancel).show();
►ClickListener
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();
    }
};
Free Web Hosting