即使在退出应用程序后,如何保留从微调器中选择的项目?

时间:2016-03-07 19:12:25

标签: android sharedpreferences android-sharedpreferences

以下是我的代码,即点击

从微调器中获取项目
public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

private Spinner spinner1,spinner2,spinner3;
private static final String[] sports = {
        "Hockey","Cricket","Football","Basketball","Badminton","Tennis"
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spinner);

    spinner1 = (Spinner)findViewById(R.id.drop_down);
    spinner2 = (Spinner)findViewById(R.id.drop_down2);
    spinner3 = (Spinner)findViewById(R.id.drop_down3);
    ArrayAdapter<String> adapter;
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item,sports);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner2.setAdapter(adapter);
    spinner3.setAdapter(adapter);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String item = parent.getItemAtPosition(position).toString();
}

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

如何保留选定的微调器&#39;即使退出申请后项目?

2 个答案:

答案 0 :(得分:2)

您可以使用SharedPreference存储所选的值position / id / string。

当您获得String item

时,只需添加此行
Editor edit = context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).edit();
edit.putString("selected_item", item);
edit.commit();

可以简单地将值检索为

context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).getString("selected_item", "");

答案 1 :(得分:0)

欲了解更多信息@AnirudhSohil你可以看到官方文档,它有一个非常详细的例子,我希望它可以帮助你。

enter image description here http://developer.android.com/training/basics/data-storage/shared-preferences.html