Метод alertDialog.getButton () дает исключение нулевого указателя для Android - PullRequest
40 голосов
/ 05 января 2011

Я планирую дать создать 3 кнопки с layout_weight = 1, не заинтересованы в настраиваемом диалоге. Так что я написал ниже код. Он не работает. Всегда кнопка да дает мне ноль. Что не так в этом коде?

  AlertDialog dialog= new AlertDialog.Builder(this).create();
            dialog.setIcon(R.drawable.alert_icon);
            dialog.setTitle("title");
            dialog.setMessage("Message");
            dialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                                                }
            });
            Button yesButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            Log.w("Button",""+yesButton);//here getting null
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f);
            yesButton.setLayoutParams(layoutParams);
            dialog.show();

С уважением, Разработчик Android.

Ответы [ 3 ]

68 голосов
/ 05 января 2011

Посмотрите здесь ответ: http://code.google.com/p/android/issues/detail?id=6360

Как сказано в комментарии № 4, вы должны вызвать show() в своем диалоговом окне, прежде чем вы сможете получить доступ к кнопкам, они не доступны заранее.Для автоматического решения о том, как изменить кнопки, как только они будут готовы, см. Ответ Микки

57 голосов
/ 30 января 2013

Это работает для меня:

AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setMessage(message)
                .setCancelable(true)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            //do smthng
                        })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //do snthn
                    }
                }).create();

        alertDialog.setOnShowListener(new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {                    //
                Button positiveButton = ((AlertDialog) dialog)
                        .getButton(AlertDialog.BUTTON_POSITIVE);
                positiveButton.setBackgroundDrawable(getResources()
                        .getDrawable(R.drawable.btn_default_holo_dark));

                Button negativeButton = ((AlertDialog) dialog)
                        .getButton(AlertDialog.BUTTON_NEGATIVE);
                positiveButton.setBackgroundDrawable(getResources()
                        .getDrawable(R.drawable.btn_default_holo_dark));
            }
        });

        alertDialog.show(); 

только в этом порядке, звоните alertDialog.setOnShowListener после create()

4 голосов
/ 05 января 2011

Спасибо, wieux. Но для новых целей понимания разработчиков я переписываю код ниже

AlertDialog dialog= new AlertDialog.Builder(this).create();             
dialog.setIcon(R.drawable.alert_icon);             
dialog.setTitle("title");            
dialog.setMessage("Message");             
dialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() {                 
    @Override                 
    public void onClick(DialogInterface arg0, int arg1) {                                                
    }             
}); 
dialog.show(); 
Button yesButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);             
Log.w("Button",""+yesButton); //here getting null             
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f);             
yesButton.setLayoutParams(layoutParams);        
...