How to Build AppCompatDialog From AlertDialog.Builder or Equivalent?

前端 未结 4 1546
无人及你
无人及你 2021-02-13 17:21

Before this I used a DialogBuilder to create AlertDialog like this

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


        
4条回答
  •  别那么骄傲
    2021-02-13 17:56

    I've just moved all my android.app.AlertDialog to android.support.v7.app.AlertDialog.

    After some testing with 4.X emulators I've found that for a simple dialog it's enough to simply change the import. But for multiple choice dialogs, additionally, you need to do AppCompatDialog alert = builder.create(); to get the Material Design style dialogs (on 4.X).

    To be clear, if you have a simple dialog like this one:

    import android.support.v7.app.AlertDialog;
    
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setIcon(resId)
    .setTitle(title)
    .setMessage(msg)
    .setCancelable(isCalncelable)
    .setPositiveButton(btn1, listener1);
    AlertDialog alert = builder.create();
    alert.show();
    

    Changing the import will suffice :)

    But for a multi choice dialog, you need to use AppCompatDialog like this:

    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatDialog;
    
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Choose something")
    .setPositiveButton(...)
    .setMultiChoiceItems(mStringArray, mSelectedArray, SomeFragment.this);
    AppCompatDialog alert = builder.create();
    alert.show();
    

    Then you get the nice Material Design look on 4.X devices.

    Now the fun part!

    For a multi choice dialog, on a 5.X device, the native version (android.app.AlertDialog) shows the check-boxes at the left, correctly following the Material Design spec. But if you use the support dialogs, then the check-boxes will appear at the right. WTF!

    On the long term, as Android 5+ gains market share, you will want to switch back to native dialogs.

提交回复
热议问题