2013-04-09 42 views
10

如何在使用AlertDialog创建DialogFragment时禁用确定/取消按钮? 我打过电话myAlertDialogFragment.getDialog(),但它总是返回null甚至一度片段显示Android:禁用DialogFragment确定/取消按钮

public static class MyAlertDialogFragment extends DialogFragment { 

    public static MyAlertDialogFragment newInstance(int title) { 
     MyAlertDialogFragment frag = new MyAlertDialogFragment(); 
     Bundle args = new Bundle(); 
     args.putInt("title", title); 
     frag.setArguments(args); 
     return frag; 
    } 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     int title = getArguments().getInt("title"); 

     return new AlertDialog.Builder(getActivity()) 
       .setIcon(R.drawable.alert_dialog_icon) 
       .setTitle(title) 
       .setPositiveButton(R.string.alert_dialog_ok, 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          ((FragmentAlertDialog)getActivity()).doPositiveClick(); 
         } 
        } 
       ) 
       .setNegativeButton(R.string.alert_dialog_cancel, 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          ((FragmentAlertDialog)getActivity()).doNegativeClick(); 
         } 
        } 
       ) 
       .create(); 
    } 
} 

我知道我可以通过虚报同时包含取消布局和OK键,但我宁愿使用AlertDialog解决方案,如果可能的

回答

25

附上您的AlertDialog变量:

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
(initialization of your dialog) 
AlertDialog alert = builder.create(); 
alert.show(); 

,然后从AlertDialogand获得按钮将它设置禁用/启用:

Button buttonNo = alert.getButton(AlertDialog.BUTTON_NEGATIVE); 
buttonNo.setEnabled(false); 

它给你机会,在运行时更改按钮属性。

然后回到你的警报变量。

AlertDialog必须取得其意见之前显示。

+2

我试过了,但它不工作,因为alert.getButton(AlertDialog.BUTTON_NEGATIVE);在alert.show()之前调用时会返回null null() 因此我不知道在哪里调用它... – user1026605 2013-04-09 20:54:39

+8

这样做,是的(我个人觉得它真的很烦人)。你想要做的是在生命周期后面的某个地方做'setEnabled()'调用,可能在'onResume()'之后。 – Delyan 2013-04-09 20:55:44

23

你需要重写在onStart()在DialogFragment,并保持到按钮的引用。然后,您可以使用该参考重新启用按钮:

Button positiveButton; 

@Override 
public void onStart() { 
    super.onStart(); 
    AlertDialog d = (AlertDialog) getDialog(); 
    if (d != null) { 
     positiveButton = d.getButton(Dialog.BUTTON_POSITIVE); 
     positiveButton.setEnabled(false); 
    } 

} 
+1

很好的回答!无论如何,你不必将'd.getButton'返回给一个Button对象。 – 2015-04-17 17:01:15

+0

它的工作原理。不需要投射:positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);足够。 – Andrey 2015-05-15 13:34:59