I am using two spinners. The items in second spinner gets populated dynamically based on the selection of the item of first spinner. I have implemented OnItemSelectedListener and overridden onItemSelected to achieve this. I am also using SharedPreferences to persist certain data to take care of screen rotation. The trouble I am facing is that, everything works perfectly fine and as expected with android version 4.0 but the same code fails to work with above versions of android(4.1, 4.2, 4.3) and selected item of second spinner resets on screen rotation. What is driving me nuts is, with android version 4.0 things work perfectly fine. Any suggestions?
4 回答
我找到了一个解决方案,虽然并不完美,但更多的是一个钩子,如果屏幕旋转,我假设第一个微调器的项目选定项目及其索引将相同(因为我正在处理自然数)所以我正在设置相应地在第二个微调器中的数据,否则在第一个微调器的 onItemSelected 侦听器中创建一个新微调器并在其中设置所需的数据。不是很干净,但对我有用(适用于 4.0 及以上版本)。
if(firstSpinnerItemSelected != 位置 || firstSpinnerItemSelected == 0){ firstSpinner.setSelection(secondSpinnerItemSelected, true); ArrayAdapter secondAdapter = new ArrayAdapter( 上下文,R.layout.spinner_item,itemList); secondSpinner.setAdapter(secondAdapter); } 别的{ secondSpinner.setSelection(secondSpinnerItemSelected, false); }
我不知道它可能与版本 > 4.0 有什么关系,但是通过将要保留的数据写入 onSaveInstanceState(Bundle out) 中的包并在 onCreate 中读取来处理配置更改可能是一个更好的主意(捆绑保存的实例)。
即使它不会“修复”您看到的奇怪行为,但它应该可以工作......
在我看来,使用 SharedPreferences 来保存该数据并不是一个好主意。同时将 Spinner 放在 onSaveInstanceState() Bundle 中并不是一个好主意。除了不可能的事实之外,这样做会导致您的新活动保留对该 Spinner 的引用,该 Spinner 保留对您旧活动的引用,这将导致大量内存泄漏。
您的 Spinner 的内容是通过某种适配器设置的。您应该确保您的新 Activity 可以重新创建该适配器。然后,将 getItemSelectedId() 或 getItemSelectedPosition() 放入 Bundle 中,这样您就可以在新的 Activity 中恢复选择。
尝试实现方法
onSaveInstaceState() // to save current selected items;
和
onRestoreInstanceState() // to select saved items.
或者您可以添加到您的清单活动标签
android:configChanges="orientation"
那么你的活动将不会被重新创建,一切都应该是一样的