Can I force the dropdown view of a spinner to stay

2019-05-05 13:59发布

问题:

I don't know if it's clear from the title what I asked, so here are some steps to reproduce (assuming you have a layout with a spinner):

  1. Tap on the spinner > dropdown list opens.
  2. Rotate the device from portrait to landscape (or vice-versa) > the list is closing.

My problem is that I would like to keep the list opened after rotating the device. I know that this is usually possible if overriding onConfigurationChanged, but I have defined a different layout for landscape mode, so in my onConfigurationChanged method I have to call setContentView and set the adapter for the landscape spinner, which closes the dropdown view that was opened in portrait mode.

Is there a way I could prevent the dropdown list from closing or perhaps forcing it to show after rotating the device?

回答1:

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.



回答2:

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.