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

时间:2018-05-17 22:39:36

标签: java android

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

目前,我的代码是:

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

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

4 个答案:

答案 0 :(得分:0)

正如我所理解的那样,您必须将selectedElement的变量类型从public int更改为public static int。此外,快速查看第一个列表显示函数switch (i)中的所有onCreateDialog个案例都应用相同的逻辑,因此它们是冗余的,只有一个案例可以使用相同的逻辑。

答案 1 :(得分:0)

解决此问题的两种方法:

  1. 使用SharedPreferences :使用SharedPreferences设置/获取您选择的元素
  2. (它会在退出应用程序后存放很长时间)

    1. 在您的CurrencyChoiceDialog中将selectedElement设为公共静态,如:
    2. (只有当你在屏幕上时才会存储)

      public static int selectedElement = -1;
      

答案 2 :(得分:0)

删除了开关盒并将其简化为一个盒子。以及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();
 }
}

答案 3 :(得分:-1)

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