Android: Create a single choice dialog with disabl

2019-08-24 04:37发布

I want to create dialog with simple single choice items. By default, no items are selected. I only want an OK and Cancel button. The OK button must remain disabled until an item is selected. Is there some built-in way of doing this or do I have to create my own custom dialog? This is currently what I have:

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

builder.setTitle(getString(R.string.lbl_MarkReviewAs))
    .setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int item)
      {
        selectedReviewStatusIndex = item;
        AlertDialog alertDialog = (AlertDialog)dialog;
        alertDialog.getButton(0).setEnabled(true);
      }
    })
    .setPositiveButton(getString(R.string.lbl_ButtonOK), new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int whichButton)
      {
        dialog.dismiss();
      }
    })
    .setNegativeButton(getString(R.string.lbl_ButtonCancel), new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int whichButton)
      {
        dialog.dismiss();
      }
    });

AlertDialog dialog =  builder.create();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
dialog.show();

The problem here is that dialog.getButton(AlertDialog.BUTTON_POSITIVE) returns null. So how do I access the positive button?

3条回答
叼着烟拽天下
2楼-- · 2019-08-24 05:19

I thing best is to subclass ListActivity. Here is example.

To make it nice set style of this activity (in manifest) to some Dialog (best choice is "@android:style/Theme.DeviceDefault.Dialog").

<activity android:name="YourDialogActivity"
    android:label="@string/title"
    android:theme="@android:style/Theme.DeviceDefault.Dialog">
    <intent-filter>
          ...
    </intent-filter>
</activity>
查看更多
Juvenile、少年°
3楼-- · 2019-08-24 05:24

you need show dialog then disable button Positive.

AlertDialog dialog =  builder.create();

dialog.show();

dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-08-24 05:37

set listener to the Item selected and enable the "OK" Button

查看更多
登录 后发表回答