简体   繁体   中英

Save State of a radio button in dialog when ok is pressed and dialog is dismissed

Currently, I have a popup dialogue that shows when I press the currency button, this dialogue contains a set of radio buttons that users can select one of them. I'm trying to get the selected radio button's state to be saved when the user pressed "OK". So that when they press the "Currency" button again, the radio button selection was the one the user chose prior to pressing "OK".

Currently, my code is this:

CurrencyChoiceDialog.java

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;


public class CurrencyChoiceDialog extends DialogFragment {

final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;


@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstance){
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            switch (i){
                case 0:
                    selectedCurrency = (String)currencies[i];
                    selectedElement = i;
                    break;
                case 1:
                    selectedCurrency = (String)currencies[i];
                    selectedElement = i;
                    break;
                case 2:
                    selectedCurrency = (String)currencies[i];
                    selectedElement = i;
                    break;
                case 3:
                    selectedCurrency = (String)currencies[i];
                    selectedElement = i;
                    break;
                default:
                    break;
            }
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
        }
    });
    return  builder.create();
  }
 }

Settings.java

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class Settings extends AppCompatActivity implements View.OnClickListener {


Button confirm;
Switch useDefault;
boolean toggle;
private CardView currency;
private CardView tipPercentage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    confirm = findViewById(R.id.saveButton);
    useDefault = findViewById(R.id.switch1);
    currency = findViewById(R.id.currencyButton);
    tipPercentage = findViewById(R.id.tipPercentageButton);

    confirm.setOnClickListener(this);
    currency.setOnClickListener(this);
    tipPercentage.setOnClickListener(this);

    final SharedPreferences sharedPreferences = getSharedPreferences("Press", 0);
    toggle = sharedPreferences.getBoolean("Switch", false);

    useDefault.setChecked(toggle);
    useDefault.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggle = !toggle;
            useDefault.setChecked(toggle);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("Switch", toggle);
            editor.apply();
        }
    });
}

@Override
public void onClick(View view) {
    Intent i;
    switch (view.getId()) {
        case R.id.saveButton:
            i = new Intent(this, MainActivity.class);
            startActivity(i);
            break;
       // TODO: Save the state once the OK button is clicked for the currency.
        case R.id.currencyButton:
            setCurrency(view);
            break;
        //  TODO: Finish implementing the changes in the seekbar and reflecting it with the percentage text, and saving that state in the application
        case R.id.tipPercentageButton:
            showDialog();
            break;

        default:
            break;
    }
}

public void setCurrency(View view) {
    CurrencyChoiceDialog currencyChoiceDialog = new CurrencyChoiceDialog();
    currencyChoiceDialog.show(getSupportFragmentManager(), "CurrencySelection");
}

public void showDialog() {
    final Dialog yourDialog = new Dialog(this);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.dialog_tippercentage, (ViewGroup) findViewById(R.id.your_dialog_root_element));
    Button yourDialogButton = (Button) layout.findViewById(R.id.your_dialog_button);
    SeekBar yourDialogSeekBar = (SeekBar) layout.findViewById(R.id.your_dialog_seekbar);
    yourDialog.setContentView(layout);
    yourDialog.show();
    yourDialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            yourDialog.dismiss();
        }
    });
 }
}

I've tried numerous solutions here but none worked. So any help would be much appreciated. This is my first time trying to make a setting's page for an application. So please make sure your answers are thorough as possible. Thanks in advance.

As I understood the problem, you have to change the variable type of selectedElement from public int to public static int . Furthermore, a quick look to your first listing shows that all switch (i) cases in the function onCreateDialog are applying the same logic, so they are redundant and you can have the same logic by just one case.

Two way to fix this:

  1. Using SharedPreferences : set/get your selectedElement using SharedPreferences

(It will store for long time, after exit from the app also)

OR

  1. Make selectedElement as public static in your in CurrencyChoiceDialog like:

(It will store only when you are on the screen)

public static int selectedElement = -1;

Removed the switch cases and simplified it into one case. As well as had the selectedElement to be static. so it becomes:

public class CurrencyChoiceDialog extends DialogFragment {

final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;


@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
         selectedCurrency = (String)currencies[i];
                    selectedElement = i;
    }
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
    }
});
return  builder.create();
 }
}

The -1 in (int cheched) here is the default selected item index (-1 means do not select any default). use this parameter to set the default selected.

    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    String[] items={"item1","item2"};
    SharedPreferences prefs=getPreferences(MODE_PRIVATE);

// If you open the dialog again, we'll put the previously saved option here..
    int checked = prefs.getInt("checked", -1);  
    
    builder.setTitle("your Title")
           .setCancelable(false)
           .setSingleChoiceItems(languages, checked , (dialog, which) -{
                if (which==0) {
                     //  if selected first item ~ code..              
                }else if (which==1){
                    //   if selected second item ~ code..
                }
// then put your selected item in Shared Preferences to save it..
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("checked",which);
                editor.apply();
            })
           .setNegativeButton(Cancel,null)
           .setPositiveButton(OK, (dialog, which) -> {
                dialog.dismiss();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM