从共享首选项中设置和检索Spinner数据

时间:2014-02-26 17:14:14

标签: android spinner sharedpreferences

我有3个Spinners,主要选择类别和另外2个From和To。

我需要的是保存最后用户的选择,并在用户下次打开应用程序时检索它。

这是我的代码:

        //Here is my spinner
    UnitSpinner = (Spinner) findViewById(R.id.UnitSpinner);
    UnitSpinner.setOnItemSelectedListener(this);
    UnitSpinner.setAdapter(new UnitArray(UnitConverter.this, R.layout.row,
            (getResources().getStringArray(R.array.my_string_array))));

    //Here is my spinners From and to
    SpinnerFrom = (Spinner) findViewById(R.id.SpinnerFrom);
    SpinnerFrom.setOnItemSelectedListener(this);
    SpinnerTo = (Spinner) findViewById(R.id.SpinnerTo);
    SpinnerTo.setOnItemSelectedListener(this);

    //MY array adapter
    UnitArrayadapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item);
    UnitArrayadapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    SpinnerFrom.setAdapter(UnitArrayadapter);
    SpinnerTo.setAdapter(UnitArrayadapter);
    UnitArrayadapter.setNotifyOnChange(true);

我知道保存它的最佳方法是在onPause中并从onCreate中检索它。

注意:我正在为我的主微调器使用自定义微调器(row.xml布局)。

感谢Advance中的任何帮助。

更新:以下是我尝试的方法:

    @Override
protected void onPause() {
    super.onPause();

    Editor editor = sharedpreferences.edit();

    int selectedPosition = UnitSpinner.getSelectedItemPosition();
    editor.putInt("spinnerSelection", selectedPosition);

    editor.commit();

我不知道它是否有效但关键是我不知道如何从我的onCreate中的Sharedprefereces中检索它!

更新2:

    private Spinner UnitSpinner;
private TextView inputValue;
private Spinner SpinnerFrom;
private Spinner SpinnerTo;
private Button ButtonConvert;
private TextView ResultView;
ArrayAdapter<String> UnitArray;
ArrayAdapter<String> UnitArrayadapter;
private Strategy currentStrategy;
private String unitfrom;
private String unitto;
private static UnitConverter instance;
ArrayAdapter<CharSequence> Adapter1;
/** SharedPreferences */
public static final String MyPREFERENCES = "MyPrefs";
public static final String inputValueNamber = "InputYourNumber";
public static final String Result = "TheResultIs";
SharedPreferences sharedpreferences;

@SuppressLint({ "ShowToast", "NewApi" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    setContentView(R.layout.mainpage);

    inputValue = (TextView) findViewById(R.id.EditTextValue);

    /** SharedPreferences */
    sharedpreferences = getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);

    if (sharedpreferences.contains(inputValueNamber)) {
        inputValue.setText(sharedpreferences
                .getString(inputValueNamber, ""));
    }

    /** SharedPreferences for Spinner */
    int selectedPosition = sharedpreferences.getInt("spinnerSelection", 0);
    /** End */

    /** End of SharedPreferences */

    Button buttonClear = (Button) findViewById(R.id.buttonClear);

    b1 = (Button) findViewById(R.id.ButtonAbout);
    b1.setOnClickListener(mb1);

    /** Hide Auto Keyboard */
    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    /** Hide Auto Keyboard End here */

    UnitSpinner = (Spinner) findViewById(R.id.UnitSpinner);
    UnitSpinner.setOnItemSelectedListener(this);

    UnitSpinner.setAdapter(new UnitArray(UnitConverter.this, R.layout.row,
            (getResources().getStringArray(R.array.my_string_array))));

    SpinnerFrom = (Spinner) findViewById(R.id.SpinnerFrom);
    SpinnerFrom.setOnItemSelectedListener(this);
    SpinnerTo = (Spinner) findViewById(R.id.SpinnerTo);
    SpinnerTo.setOnItemSelectedListener(this);
    UnitArrayadapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item);
    UnitArrayadapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    SpinnerFrom.setAdapter(UnitArrayadapter);
    SpinnerTo.setAdapter(UnitArrayadapter);
    UnitArrayadapter.setNotifyOnChange(true);
    ResultView = (TextView) findViewById(R.id.TextViewResult);
    ResultView.setClickable(false);
    ButtonConvert = (Button) findViewById(R.id.Button01);
    ButtonConvert.setOnClickListener(this);

    /** initialization */
    currentStrategy = new Temperature();
    instance = this;
}

private void setRetainInstance(boolean b) {
    // TODO Auto-generated method stub

}

/** For Icons */
public class UnitArray extends ArrayAdapter<String> {

    public UnitArray(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView,
            ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.row, parent, false);

        TextView label = (TextView) row.findViewById(R.id.SelectUnits);
        label.setText(getResources()
                .getStringArray(R.array.my_string_array)[position]);

        TextView sub = (TextView) row.findViewById(R.id.sub);
        sub.setText(getResources().getStringArray(
                R.array.my_string_array_sub)[position]);

        ImageView icon = (ImageView) row.findViewById(R.id.image);
        icon.setImageResource(arr_images[position]);

        return row;
    }
}

public static UnitConverter getInstance() {
    return instance;
}

public void onItemSelected(AdapterView<?> parent) {
}

public void onNothingSelected(AdapterView<?> parent) {

}

public void onItemSelected(AdapterView<?> parent, View v, int position,
        long id) {
    if (v.getParent() == UnitSpinner) {

        switch (position) {
        case 0:
            setStrategy(new Temperature());
            break;

        case 1:
            setStrategy(new Weight());
            break;

        case 2:
            setStrategy(new Length());
            break;

        case 3:
            setStrategy(new Power());
            break;

        case 4:
            setStrategy(new Energy());
            break;

        case 5:
            setStrategy(new Velocity());
            break;

        case 6:
            setStrategy(new Area());
            break;

        case 7:
            setStrategy(new Volume());
            break;
        }

        fillFromToSpinner(position);

        SpinnerFrom.setSelection(0);
        SpinnerTo.setSelection(0);

        unitfrom = (String) (SpinnerFrom.getItemAtPosition(0).toString());
        unitto = (String) (SpinnerTo.getItemAtPosition(0).toString());

        /** reset the result */
        ResultView.setText("");

    } else if (v.getParent() == SpinnerFrom) {
        unitfrom = (String) (SpinnerFrom.getSelectedItem().toString());
    }

    else if (v.getParent() == SpinnerTo) {
        unitto = (String) (SpinnerTo.getSelectedItem().toString());
    }
}

private void fillFromToSpinner(int position) {

    switch (position) {
    case 0:
        fillSpinnerWithTempUnit();
        break;

    case 1:
        fillSpinnerWithWeightUnit();
        break;

    case 2:
        fillSpinnerWithLengthUnit();
        break;

    case 3:
        fillSpinnerWithPowerUnit();
        break;

    case 4:
        fillSpinnerWithenErgyUnit();
        break;

    case 5:
        fillSpinnerWithVelocityUnit();
        break;

    case 6:
        fillSpinnerWithAreaUnit();
        break;

    case 7:
        fillSpinnerWithVolumeUnit();
        break;
    }

}

private void fillSpinnerWithTempUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources()
            .getString(R.string.temperatureunitc));
    UnitArrayadapter.add(getResources()
            .getString(R.string.temperatureunitf));
    UnitArrayadapter.add(getResources().getString(
            R.string.temperatureunitkelvin));
    UnitArrayadapter.notifyDataSetChanged();
}

private void fillSpinnerWithWeightUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources().getString(R.string.weightunitkg));
    UnitArrayadapter.add(getResources().getString(R.string.weightunitgm));
    UnitArrayadapter.add(getResources().getString(R.string.weightunitlb));
    UnitArrayadapter
            .add(getResources().getString(R.string.weightunitounce));
    UnitArrayadapter.add(getResources().getString(R.string.weightunitmg));
    UnitArrayadapter.notifyDataSetChanged();
}

private void fillSpinnerWithLengthUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitmile));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitkm));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitm));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitcm));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitmm));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitinch));
    UnitArrayadapter.add(getResources().getString(R.string.lengthunitfeet));
}

private void fillSpinnerWithPowerUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources().getString(R.string.powerunitwatts));
    UnitArrayadapter.add(getResources().getString(
            R.string.powerunithorseposer));
    UnitArrayadapter.add(getResources().getString(
            R.string.powerunitkilowatts));
}

private void fillSpinnerWithenErgyUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources().getString(
            R.string.energyunitcalories));
    UnitArrayadapter.add(getResources()
            .getString(R.string.energyunitjoules));
    UnitArrayadapter.add(getResources().getString(
            R.string.energyunitkilocalories));

}

private void fillSpinnerWithVelocityUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources()
            .getString(R.string.velocityunitkmph));
    UnitArrayadapter.add(getResources().getString(
            R.string.velocityunitmilesperh));
    UnitArrayadapter.add(getResources().getString(
            R.string.velocityunitmeterpers));
    UnitArrayadapter.add(getResources().getString(
            R.string.velocityunitfeetpers));
}

private void fillSpinnerWithAreaUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources().getString(R.string.areaunitsqkm));
    UnitArrayadapter
            .add(getResources().getString(R.string.areaunitsqmiles));
    UnitArrayadapter.add(getResources().getString(R.string.areaunitsqm));
    UnitArrayadapter.add(getResources().getString(R.string.areaunitsqcm));
    UnitArrayadapter.add(getResources().getString(R.string.areaunitsqmm));
    UnitArrayadapter.add(getResources().getString(R.string.areaunitsqyard));
}

private void fillSpinnerWithVolumeUnit() {
    UnitArrayadapter.clear();
    UnitArrayadapter.add(getResources()
            .getString(R.string.volumeunitlitres));
    UnitArrayadapter.add(getResources().getString(
            R.string.volumeunitmillilitres));
    UnitArrayadapter.add(getResources()
            .getString(R.string.volumeunitcubicm));
    UnitArrayadapter.add(getResources().getString(
            R.string.volumeunitcubiccm));
    UnitArrayadapter.add(getResources().getString(
            R.string.volumeunitcubicmm));
    UnitArrayadapter.add(getResources().getString(
            R.string.volumeunitcubicfeet));
}

public void onClick(View v) {

    if (v == ButtonConvert) {
        if (!inputValue.getText().toString().equals("")) {
            double in = Double.parseDouble(inputValue.getText().toString());
            double result = currentStrategy.Convert(unitfrom, unitto, in);
            ResultView.setText(String.format("%.02f", result));
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow(getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } else {
            ResultView.setText("");
        }
    }
}

private void setStrategy(Strategy s) {

    currentStrategy = s;
}

@Override
protected void onPause() {
    super.onPause();

    Editor editor = sharedpreferences.edit();

    String ive = inputValue.getText().toString();
    editor.putString(inputValueNamber, ive);

    int selectedPosition = UnitSpinner.getSelectedItemPosition();
    editor.putInt("spinnerSelection", selectedPosition);

    editor.commit();

}

1 个答案:

答案 0 :(得分:1)

要检索数据(就像你说的那样,你会把它放在onCreate中),你会做类似的事情:

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
int selection = sharedpreferences.getInt("spinnerSelection",0);

基本上它的作用是它试图抓取映射到字符串“spinnerSelection”的任何int,如果没有映射到它,selection被设为0,getInt中的第二个参数。