2017-01-08 35 views
0

我已經查看了大多數帖子在這裏stackoverflow,但我不能得到這個工作。除非所有字段完成,否則我希望禁用正向按鈕(寄存器)。在AlertDialog中禁用正向按鈕

我該如何做到這一點?

public static class UsernameDialogFragment extends DialogFragment { 


    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     LayoutInflater inflater = getActivity().getLayoutInflater(); 


     builder.setView(inflater.inflate(R.layout.ipcamaccount, null)) 
       .setPositiveButton(R.string.action_register, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(final DialogInterface dialog, int id) { 

         //some other code 
         } 
        } 
       }); 

     builder.setView(inflater.inflate(R.layout.ipcamaccount, null)) 
       .setNegativeButton(R.string.action_cancel, null); 


     return builder.create(); 
    } 
    } 
+1

創建自定義對話框。 – Rahul

回答

0

我用一種不同的方法來完成這件事。希望它可以爲別人節省麻煩。我在RecyclerView適配器中使用它,所以你必須設置上下文。我不知道這是否是最優雅的方式,但它工作得很好。

下面是代碼:

private void myDialog() { 

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext); 
    dialogBuilder.setView(R.layout.ipcamaccount); 

    dialogBuilder.setPositiveButton(R.string.action_register, null); 
    dialogBuilder.setNegativeButton(R.string.action_cancel, null); 

    final AlertDialog alertDialog = dialogBuilder.create(); 
    alertDialog.show(); 

    Button positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); 
      positiveButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      onPositiveButtonClicked(alertDialog); 
     } 
    }); 

    Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE); 

    negativeButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      onNegativeButtonClicked(alertDialog); 
     } 
    }); 
} 

private void onPositiveButtonClicked(AlertDialog alertDialog) { 

     if(some condition) { 

     alertDialog.dismiss(); 

     Toast.makeText(mContext, "Some toast", Toast.LENGTH_LONG).show(); 

    }else { 
     Toast.makeText(mContext, "Some other toast", Toast.LENGTH_LONG).show(); 
    } 

} 

private void onNegativeButtonClicked(AlertDialog alertDialog) { 
    alertDialog.dismiss(); 
} 
0

在積極的按鈕偵聽,驗證數據,如果數據有效,則繼續進行,如果不顯示有關錯誤的烤麪包。

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