Can I force the dropdown view of a spinner to stay visible on orientation changes?

人盡茶涼 提交于 2019-12-05 15:26:18

I found a very ugly solution to this (the 'action' takes place in the onConfigurationChanged method):

  1. Before calling setContentView, check if the dropdown view is shown (*) and if so, save the position that is currently selected in the spinner (int pos = spinner.getSelectedItemPosition()).

  2. After calling setContentView and setting the spinner adapter, if the dropdown view was shown in step 1, force the dropdown view to show by calling performClick on the spinner:

    spinner.setSelection(pos);// this way we make sure that the same item
                              // remains selected after rotating the device
    spinner.performClick(); //show the dropdown view 
    

(*) Checking if the dropdown view is shown is the trickier part. I haven't found (yet) a method that lets me know whether the dropdown view is shown, so I had to do the following:

  • Hold the spinner's pressed state in a boolean variable (named, for example, isClicked).

  • Set an onTouchListener for the spinner and in the onTouch method set isClicked to true (when tapping the spinner, the dropdwon view opens, so isClicked == true means that the dropdown view is shown).

  • Override onKeyDown or onKeyUp and when back button is pressed, if isClicked is true, set it to false (I assumed that pressing back with isClicked==true means closing the dropdown view).

  • Use the value of isClicked in onConfigurationChanged method to check if the dropdown view is shown.

Like I said, it's an ugly fix, but it's the only one I could come up with until now. If anybody has other ideas, please post them.

By default the behavior on switching from portrait to landscape is restart your Activity. So, you can save the spinner state to somewhere, for example to SharedPreferences and read it when restarting the activity(in onCreate() or onResume()) methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!