微调框未保存最后选择的值

时间:2018-07-05 14:29:31

标签: android android-fragments sharedpreferences android-spinner

我的android应用程序中有一个微调器,每当我转到其他片段并返回时,微调器都会转到第一项。我只想要微调器保留值。以下是我如何设置微调器。

private void setupSpinner(){
    roundSpinnerMap = new HashMap<>();
    roundSpinnerItems = new ArrayList<>();
    //Get the day of the week in order to figure out which rounds and variables are needed.
    Calendar c = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy", Locale.US);
    Date d = null;
    try {
        d = format.parse(mDay);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    c.setTime(d);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
    //If the day is Sunday then dayOfWeek is 7, not 0.
    if(dayOfWeek == 0){
        dayOfWeek = 7;
    }
    for (Models.Round r:rounds) {
        //For each round get the completed and total amount.
        int[] partWhole = models.getCompletedOfTotal(r.getName(), mDay, dayOfWeek, nameText.getText().toString());
        String readable = r.getName() +" (Completed " + partWhole[0] + " of " + partWhole[1] + ")";
        //If there are none to complete, then do not show/add the option.
        if(!readable.contains("of 0")){
            roundSpinnerMap.put(readable, r.getName());
            roundSpinnerItems.add(readable);
        }
    }
    ArrayAdapter<String> roundAdapter = new ArrayAdapter<>(
            getActivity(), R.layout.simple_spinner_item, roundSpinnerItems
    );
    roundAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    roundSpinner.setAdapter(roundAdapter);
    roundSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String readable = roundSpinner.getSelectedItem().toString();
            mRound = roundSpinnerMap.get(readable);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

下面是我的onCreate方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    models = new ModelsHandler(getActivity());
    if (getArguments() != null) {
        mHome = getArguments().getBoolean(ARG_HOME);
        mUser = getArguments().getString(ARG_USER);
        mFacility = getArguments().getString(ARG_FACILITY);
    }
    calendar = Calendar.getInstance();
    mDay = format.format(calendar.getTime());
    sharedPreferences = getActivity().getSharedPreferences(MainActivity.PREFERENCES, Context.MODE_PRIVATE);
    rounds = models.getAllRounds();
    rise = AnimationUtils.loadAnimation(getActivity(), R.anim.rise_vert);
    sink = AnimationUtils.loadAnimation(getActivity(), R.anim.sink_vert);
    if (mListener == null){
        mListener = (OnFragmentInteractionListener) getActivity();
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_splash, container, false);

    roundsButton = view.findViewById(R.id.roundsButton);
    calendarButton = view.findViewById(R.id.calendarButton);
    contactButton = view.findViewById(R.id.contactButton);
    syncMainButton = view.findViewById(R.id.syncMainButton);
    trendButton = view.findViewById(R.id.trendButton);
    prefSyncButton = view.findViewById(R.id.prefSyncButton);
    startSyncButton = view.findViewById(R.id.startSyncButton);
    contactDevButton = view.findViewById(R.id.contactDevButton);
    contactServiceButton = view.findViewById(R.id.contactServiceButton);
    roundSpinner = view.findViewById(R.id.roundSpinner);
    roundDateText = view.findViewById(R.id.roundDateText);
    errorRoundText = view.findViewById(R.id.roundsErrorText);
    nameText = view.findViewById(R.id.nameText);
    progressBar2 = view.findViewById(R.id.progressBar2);

    errorRoundText.setVisibility(View.GONE);
    nameText.setText(sharedPreferences.getString(MainActivity.USER_SESSION_KEY,""));

    progressBar2.setVisibility(View.GONE);
    roundDateText.setText(format.format(calendar.getTime()));
    roundDateText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchDatePicker();
        }
    });

    contactActionsOpen = false;
    syncActionsOpen = false;
    if(rounds == null || rounds.isEmpty()){
        errorRoundText.setVisibility(View.VISIBLE);
        UtilityPole.initDefaultRounds(models);
        rounds = models.getAllRounds();
        Toast.makeText(getContext(), getResources().getString(R.string.errorRound), Toast.LENGTH_LONG).show();
    }
    setupSpinner();
    initializeAnimationButtons();
    initializeButtonActions();

    return view;
}

我尝试使用共享首选项,但是没有用(也许我不知道如何正确使用它,因为我是Android新手。)。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您将其存储为静态值。自从我使用android api以来已经有一段时间了,所以这不会太准确。只要替换正确的方法调用,它就会起作用

//have a private static field variable
private static int spinnerValue = 0;

private void getSpinner()
{
    spinnerValue = spinner.getCurrentValue();
}

private void setSpinner()
{
    soinner.setValue(spinnerValue);
}

这是因为static关键字使变量保留在所有类中,即使该类已通过垃圾回收被破坏了。

What does the 'static' keyword do in a class?

所以这可能就是您要寻找的

答案 1 :(得分:0)

我无法评论您的问题,所以我给出一个一般性的答案

保存并恢复纺锤中的值

enter image description here

步骤1-将保存的值的IndexNumber保存在应用程序本地的微调器中。

步骤2-以您的IndexNumber方法检索保存的onCreate并使用

setSelection方法将值设置为微调框。