alertDialog.getButton()方法给出了空指针exceptionandroid

Iam计划创build与layout_weight = 1的3个button,对定制对话框不感兴趣。所以我写下面的code.It不工作。总是是button给我空。 这个代码有什么错误?

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开发人员。

Solutions Collecting From Web of "alertDialog.getButton()方法给出了空指针exceptionandroid"

请看这里的答案: http : //code.google.com/p/android/issues/detail?id = 6360

正如它在注释#4中所说的那样,您必须在对话框中调用show()才能访问这些button,事先不可用。 有关如何在准备就绪后立即修改button的自动解决scheme,请参阅Mickeys回答

这适用于我:

 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(); 

只有按照这个顺序,在create()之后调用alertDialog.setOnShowListener

谢谢wieux.But为新的开发者理解目的Iam重写下面的代码

  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);