Search code examples
androidandroid-radiobutton

how to show selected value in alertDialog


Hi all in my application I am using AlertDialog, in this I have 3 values. User select one value and selected value is stored in sharepreference. I want to use this saved value and by default want to set this value as selected in radio button. Following is my code.

private void getFontSize()
{

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    final SharedPreferences.Editor editor = sharedPreferences.edit();

    String selectedSize = sharedPreferences.getString("fontSize", "Medium");


    final CharSequence[] items = {" Small "," Medium "," Large "};

    ArrayList<CharSequence> arrItems=new ArrayList<CharSequence>(Arrays.asList(items));
    int prevSelectedIndex = arrItems.indexOf(selectedSize);


    // Creating and Building the Dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select The Font Size");
    builder.setSingleChoiceItems(items, prevSelectedIndex, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {


            switch(item)
            {
                case 0:
                    Constants.fontSize = "Small";
                    editor.putString("fontSize",Constants.fontSize);
                    editor.commit();

                    break;
                case 1:
                    Constants.fontSize = "Normal";
                    editor.putString("fontSize",Constants.fontSize);
                    editor.commit();

                    break;
                case 2:
                    Constants.fontSize = "Large";
                    editor.putString("fontSize",Constants.fontSize);
                    editor.commit();
                    break;


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

Here if saved value is null then I am using "Medium" as selectedSize value. How I can show selected radio button, so when user run this application again then it shows radio button of Medium (or other if user selected other) as selected. Any suggestion will be appreciatd, Thanks in advance

enter image description here.


Solution

  • Pass selectedSize as second parameter to setSingleChoiceItems method as:

    ArrayList<CharSequence> arrItems=new ArrayList<CharSequence>(Arrays.asList(items));
    int prevSelectedIndex = arrItems.indexOf(selectedSize);
    builder.setSingleChoiceItems(items, prevSelectedIndex,...