savedinstancestate用于使用微调器更改文本

时间:2016-06-03 23:30:12

标签: android

所以我有一个允许用户选择语言的微调器(例如英语,西班牙语,法语)。单击时,它会将屏幕上的文本更改为所选的相应语言。文本按预期更改,甚至在屏幕旋转中也会更改。但问题是,如果我单击手机上暂时关闭应用程序的主页按钮,或者我关闭手机屏幕上的主屏幕按钮。每当我重新打开应用程序时,它都不会保存我选择的语言选择,如果我点击西班牙语或法语,它会恢复为英语,而且旋转器仍然具有所选语言。

如何在这种特殊情况下保存选择?

langSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (parent.getItemAtPosition(pos).toString().equals("Spanish")){
                questionTxt.setText(questionSpanishTxt);
                Log.e("langSpin", "onItemSelected: spanish");
            }

            if (parent.getItemAtPosition(pos).toString().equals("French")){
                questionTxt.setText(questionFrenchTxt);
                Log.e("langSpin", "onItemSelected: french");
            }

            if (parent.getItemAtPosition(pos).toString().equals("English")){
                questionTxt.setText(questionEnglishTxt);
                Log.e("langSpin", "onItemSelected: english");
            }
        }

1 个答案:

答案 0 :(得分:1)

将您的位置保留在实例变量中。在活动onResume时分配最后一个位置。

int position=0; // Default
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    langSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

            position=pos; // Assign position as "latest"

            if (parent.getItemAtPosition(pos).toString().equals("Spanish")){
                questionTxt.setText(questionSpanishTxt);
                Log.e("langSpin", "onItemSelected: spanish");
            }

            if (parent.getItemAtPosition(pos).toString().equals("French")){
                questionTxt.setText(questionFrenchTxt);
                Log.e("langSpin", "onItemSelected: french");
            }

            if (parent.getItemAtPosition(pos).toString().equals("English")){
                questionTxt.setText(questionEnglishTxt);
                Log.e("langSpin", "onItemSelected: english");
            }
        }
        *
}
@Override
protected void onResume() {
    Toast.makeText(MainActivity.this, "position" + position, Toast.LENGTH_SHORT).show();
    langSpin.setSelection(position);   // Set latest position 
    questionTxt.setText(langSpin.getSelectedItem().toString()); // Set text from spinner selection.
    super.onResume();
}