I have the following Dialog code but the problem is that the selection takes effect before I press the OK button. What should I do to make the selection take effect after the OK button is pressed?

public void cropSelect()
{
    final CharSequence[] cropType = {"Wheat","Corn","Soybean"};
    AlertDialog.Builder builder = new AlertDialog.Builder(MainContext.myContext);
    builder.setTitle("Choose Crop");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {}
    });

    builder.setSingleChoiceItems(cropType, -1, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            if("Wheat".equals(cropType[which])){
                cropSelect = "Wheat";
            }
            else if("Corn".equals(cropType[which])){
                cropSelect = "Corn";
            }
            else if("Soybean".equals(cropType[which])){
                cropSelect = "Soybean";
            }

        }
    });
    builder.show();
有帮助吗?

解决方案

You'd want to save what they select in the onClick, but not set it to the global cropSelect variable until the onClick of the positive button. Right now you just immediately write the cropSelect variable when they touch the item.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top