2013-05-19 63 views
1

我想創建一個AlertDialog,其中包含一個下一個和一個關閉按鈕,併爲「不再顯示」複選框。我使用DialogFragment的支持庫。下面的代碼只是工作正常,但我想用我自己的XML佈局此AlertDialog:Android在DialogFragment中創建一個自定義AlertDialog

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

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

       builder.setTitle("ASDASDAS") 
       .setPositiveButton(R.string.hello_world, 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          ((MainActivity)getActivity()).doPositiveClick(); 
         } 
        } 
       ) 
       .setNegativeButton(R.string.cancel, 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          ((MainActivity)getActivity()).doNegativeClick(); 
         } 
        } 
       ); 
       return builder.create(); 
    } 

是否有可能使用自己的XML佈局創建此AlertDialog?在R.layout.your_custom_dlg

<style name="IconsDialog" parent="@android:style/Theme.Dialog"> 
    <item name="android:backgroundDimEnabled">true</item> 
    <item name="android:windowBackground">@drawable/icons_dlg_bg</item> 
    <item name="android:windowNoTitle">true</item> 
</style> 

設置自定義警報佈局:

+2

看看這個 http://stackoverflow.com/questions/2795300/how-to-implement-a-custom-alertdialog-view –

回答

1

您可以使用對話是這樣的:

private void showIconsDlg(final int btnId) { 
      // Use a custom style: IconsDialog 
    final Dialog dlg = new Dialog(mContext, R.style.IconsDialog); 
      // Use a custom layout: 
    dlg.setContentView(R.layout.your_custom_dlg); 

    // Find and init Views 
    GridView grid = (GridView) dlg.findViewById(R.id.icon_grid); 


    grid.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
          ... 

     } 
    }); 

    dlg.show(); 

} 

這是主題:IconsDialog。

3

這是如何在DialogFragment中使用自己的xml佈局創建完全自定義的AlertDialog。

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

    // Inflate and set the layout for the dialog 
    // Pass null as the parent view because its going in the dialog layout 
    builder.setView(inflater.inflate(R.layout.dialog_signin, null)) 
    // Add action buttons 
      .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 
        // sign in the user ... 
       } 
      }) 
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        LoginDialogFragment.this.getDialog().cancel(); 
       } 
      });  
    return builder.create();