1. 程式人生 > >Android 覆蓋AlertDialog裡的按鈕事件並顯示Toast

Android 覆蓋AlertDialog裡的按鈕事件並顯示Toast

先看下面程式碼,點選yes或者no都不會觸發Toast

AlertDialog.Builder builder = new AlertDialog.Builder(MyWebViewTest.this);
builder.setTitle("這是標題");
builder.setMessage("這是內容");
builder.setNegativeButton("no",new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(),"no",Toast.LENGTH_LONG);
    }
});
builder.setPositiveButton("yes",new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(),"yes",Toast.LENGTH_LONG);
    }
});
builder.show();


改進(覆蓋按鈕的OnClickListener,就可以觸發Toast,顯示在對話方塊上):

AlertDialog.Builder builder = new AlertDialog.Builder(MyWebViewTest.this);
                builder.setTitle("這是標題");
                builder.setMessage("這是內容");
                builder.setNegativeButton("no",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(getApplicationContext(),"no",Toast.LENGTH_LONG);
                    }
                });
                builder.setPositiveButton("yes",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(getApplicationContext(),"yes",Toast.LENGTH_LONG);
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();//這裡必須先show,下面才能獲取到button,否則報空指標
                dialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getApplicationContext(),"yes",Toast.LENGTH_LONG).show();
                    }
                });
                dialog.getButton(Dialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getApplicationContext(),"no",Toast.LENGTH_LONG).show();
                    }
                });