繁体   English   中英

当按下确定并关闭对话框时,保存对话框中单选按钮的状态

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

目前,当我按下货币按钮时,我有一个弹出对话框,该对话框包含一组单选按钮,用户可以选择其中一个。 我试图在用户按下“确定”时保存所选单选按钮的状态。 因此,当他们再次按下“货币”按钮时,单选按钮选择是用户在按下“确定”之前选择的那个。

目前,我的代码是这样的:

货币选择对话框.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();
  }
 }

设置.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();
        }
    });
 }
}

我在这里尝试了很多解决方案,但没有一个奏效。 所以任何帮助将不胜感激。 这是我第一次尝试为应用程序制作设置页面。 因此,请确保您的回答尽可能详尽。 提前致谢。

据我了解,您必须将selectedElement的变量类型从public int更改为public static int 此外,快速查看您的第一个清单会发现onCreateDialog函数中的所有switch (i)案例都应用了相同的逻辑,因此它们是多余的,您可以仅通过一个案例拥有相同的逻辑。

解决此问题的两种方法:

  1. 使用SharedPreferences :使用设置/获取您的selectedElement SharedPreferences

(它会存储很长时间,退出应用程序后也会)

或者

  1. 在 CurrencyChoiceDialog 中将selectedElement 设为公共静态,例如:

(它只会在你在屏幕上时存储)

public static int selectedElement = -1;

移除了开关盒并将其简化为一个案例。 以及 selectedElement 是静态的。 所以它变成:

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();
 }
}

这里的(int cheched)中的 -1 是默认的选中项索引(-1 表示不选择任何默认值)。 使用此参数设置默认选择。

    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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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