在Android中,您可以使用setPositiveButton()
和setNegativeButton()
方法為AlertDialog
設(shè)置按鈕及其點(diǎn)擊事件
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showAlertDialog(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("這是一個(gè)AlertDialog");
// 設(shè)置確定按鈕及其點(diǎn)擊事件
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "點(diǎn)擊了確定按鈕", Toast.LENGTH_SHORT).show();
}
});
// 設(shè)置取消按鈕及其點(diǎn)擊事件
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "點(diǎn)擊了取消按鈕", Toast.LENGTH_SHORT).show();
}
});
// 創(chuàng)建并顯示AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
在這個(gè)例子中,我們首先創(chuàng)建了一個(gè)AlertDialog.Builder
對(duì)象。然后,我們使用setPositiveButton()
和setNegativeButton()
方法分別設(shè)置確定和取消按鈕及其點(diǎn)擊事件。最后,我們調(diào)用create()
方法創(chuàng)建AlertDialog
對(duì)象,并調(diào)用show()
方法將其顯示出來。
當(dāng)用戶點(diǎn)擊其中一個(gè)按鈕時(shí),相應(yīng)的onClick()
方法將被調(diào)用,您可以在該方法中執(zhí)行所需的操作。