2013-04-09 88 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