AlertDialog是個很常用的小對話框,可以用來顯示一些簡單的訊息,或是提示使用者決定等等,常見的像是確認的動作或是輸入有問題
setTitle():設定對話框標題。
setMessage():設定對話框訊息
setCancelable():設定對話框是否可以點選對話框外部或返回鍵來取消
setPositiveButton():在對話框中加入右側的按鈕
setNegativeButton():在對話框中加入左側的按鈕
setNeutralButton():在對話框中加入中立的按鈕
馬上來看程式碼範例
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
builder.setTitle("標題");
builder.setMessage("內容");
builder.setPositiveButton("右邊", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"右邊的按鍵",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("左邊", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"左邊的按鍵",Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButton("中間", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"中間的按鍵",Toast.LENGTH_SHORT).show();
}
});
builder.show(); //若沒有show對話框不會出來
}
});
}
}
另外一種用法就是可以當作列表來使用
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String[] str = {"新北市","台北市","桃園市","台中市","台南市","高雄市"};
builder.setTitle("列表");
builder.setItems(str, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, str[i], Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
});
}