0

I am displaying RadioButtons in a Sample AlertDialog.

AlertDialog levelDialog;
final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};

    // Creating and Building the Dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Select The Difficulty Level");

    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {


            switch(item)
            {
                case 0:
                    // Your code when first option selected
                    break;
                case 1:
                    // Your code when 2nd  option selected
                    break;
                case 2:
                    break;
                case 3:
                    break;

            }

          //  levelDialog.dismiss();
        }
    });

    builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    levelDialog = builder.create();
    levelDialog.show();

I am getting this as output

enter image description here

I need to disable the 3rd option "HARD". Means I want to display the item, but not selectable. It should be in disable mode.

Can it be implemented by modifying this code? Or Should I inflate custom layout and set it on the builder.setView()?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Jack
  • 223
  • 3
  • 13

1 Answers1

2

An alternative hacky way is to grab a reference to your view by subscribing to onShow event of the dialog, and change the onClick handlers.

final AlertDialog levelDialog = builder.create();

final int itemPositionToDisable = 2;

levelDialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {

        final ListView listView = levelDialog.getListView();

        //Store a reference to the default listener. We need to call it for references that have not been disabled.
        final AdapterView.OnItemClickListener defaultOnItemClickListener = listView.getOnItemClickListener();

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

                if(position != itemPositionToDisable)
                    defaultOnItemClickListener.onItemClick(parent, view,position, id);
            }
        });

        AppCompatCheckedTextView view = (AppCompatCheckedTextView) listView.getChildAt(itemPositionToDisable);

        //Disable on click listener so that checkbox is not activated.
        view.setOnClickListener(null);

        //Disable the view.
        view.setEnabled(false);
    }
});

levelDialog.show();
Komal12
  • 3,340
  • 4
  • 16
  • 25
Puneet
  • 653
  • 1
  • 7
  • 18