Remember what was selected in single choice AlertD

2019-03-04 09:56发布

问题:

I have an AlertDialog which displays an array into a single selected choice:

    protected boolean blFrom, blTo;
protected void showSelectToDialog() {
    boolean[] checkedDate = new boolean[toDate.length];
    int count = toDate.length;

    DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //TODO Auto-generated method stub
            onChangeSelectedTo(which);
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select To Year");
    builder.setSingleChoiceItems(toDate, count, setD2);

    builder.setCancelable(true);
    builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    dialog2 = builder.create();
    dialog2.show();
}

protected void onChangeSelectedTo(int j) {
    bTo.setText(toDate[j]);
    sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
    blTo = true;
    displayToast(String.valueOf(sTo));
    to = j;
    dialog.dismiss();
}

What I want to do is the first time it loads it should display the default. Once I select a choice and the dialog closes and I bring up the same dialog again it should show the previously selected choice I made and scroll to it.

How do I accomplish it?

As of right now, I can get the selected position but what next?

回答1:

You can store the chosen value in a variable of your Activity or using SharedPreferences