简体   繁体   English

屏幕方向更改时如何处理微调框?

[英]How to handle Spinners when screen orientation changes?

I have two Spinners. 我有两个微调器。 In onCreate i setup listeners for them. onCreate我为他们设置监听器。 At some other places i populate them. 在其他一些地方,我会填充它们。

Now I am not sure what the best practice is for handling these spinners when screen orientation changes. 现在,我不确定在屏幕方向发生变化时处理这些微调框的最佳做法是什么。 Should i store all values and selected item in sharedPreferences somehow or in savedInstanceState ? 我应该将所有值和选定的项目以某种方式存储在sharedPreferences还是保存在savedInstanceState

If you can, please advise me in a prefered way and also include some sample code for handling spinners. 如果可以的话,请以一种首选的方式告诉我,并包括一些处理微调框的示例代码。 The goal here is to keep the values and selected item thru the lifecycle. 此处的目标是在生命周期中保留值和所选项目。

I will include code at request or if needed. 我将根据要求或在需要时提供代码。

Thanks 谢谢

Try this, onSaveInstanceState for Screen Orientation for saving your selected value of spinner,According to my choice shared preference is not good choice for saving selected values of spinner. 尝试此操作, onSaveInstanceState用于“屏幕方向”以保存您选定的微调器值,根据我的选择, shared preference不是保存选定的微调器值的好选择。

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("mySpinner", mySpinner.getSelectedItemPosition());
    // do this for each or your Spinner
 }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // initialize all your visual fields        
    if (savedInstanceState != null) {
        mySpinner.setSelection(savedInstanceState.getInt("mySpinner", 0));
        // do this for each of your text views
    }
}

Add android:configChanges="orientation|screenSize" in your AndroidManifest file, it will keep spinner value selected on orientation change. 在您的AndroidManifest文件中添加android:configChanges="orientation|screenSize" ,它将在方向更改时保持选定的微调器值。

User Spinner Like this: 用户微调器是这样的:

mSpinner = findViewById(R.id.spinner);

    ArrayList<String> stringArrayList = new ArrayList<>();

    for (int i = 0; i < 6; i++) {

        stringArrayList.add("List Item " + i);

    }

    ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringArrayList);
    spinner.setAdapter(arrayAdapter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM