AlertDialog OnClickListener 方法分析
方法簽名
public void onClick(DialogInterface dialogInterface, int which)
dialogInterface 參數,代表視窗物件本身,可以改變視窗的設定。
public class MainActivity extends Activity {
private AlertDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DialogInterface.OnClickListener event = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
AlertDialog dialog = (AlertDialog) dialogInterface;
dialog.setTitle("按下後變更了標題");
}
};
dialog = new AlertDialog.Builder(this)
.setTitle("標題")
.setPositiveButton("正邊按鈕", event)
.show();
Button button = new Button(this);
button.setText("顯示視窗");
setContentView(button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.show();
}
});
}
}
which 參數,用來判斷使用者按下哪個按鈕。
public class MainActivity extends Activity {
private AlertDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DialogInterface.OnClickListener event = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == AlertDialog.BUTTON_POSITIVE) {
Toast.makeText(getApplicationContext(), "按了正邊", Toast.LENGTH_SHORT).show();
}
else if (which == AlertDialog.BUTTON_NEUTRAL) {
Toast.makeText(getApplicationContext(), "按了中間", Toast.LENGTH_SHORT).show();
}
else if (which == AlertDialog.BUTTON_NEGATIVE) {
Toast.makeText(getApplicationContext(), "按了反邊", Toast.LENGTH_SHORT).show();
}
}
};
dialog = new AlertDialog.Builder(this)
.setTitle("標題")
.setPositiveButton("正邊按鈕", event)
.setNeutralButton("中間按鈕", event)
.setNegativeButton("反邊按鈕", event)
.show();
Button button = new Button(this);
button.setText("顯示視窗");
setContentView(button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.show();
}
});
}
}