Last active
May 3, 2023 16:01
-
-
Save kakajika/a236ba721a5c0ad3c1446e16a7423a63 to your computer and use it in GitHub Desktop.
Avoid taking window focus by Android Spinner's Dropdown to keep setSystemUiVisibility flags (such as Immersive Mode).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.widget.ListPopupWindow; | |
import android.widget.PopupWindow; | |
import android.widget.Spinner; | |
public static void avoidSpinnerDropdownFocus(Spinner spinner) { | |
try { | |
Field listPopupField = Spinner.class.getDeclaredField("mPopup"); | |
listPopupField.setAccessible(true); | |
Object listPopup = listPopupField.get(spinner); | |
if (listPopup instanceof ListPopupWindow) { | |
Field popupField = ListPopupWindow.class.getDeclaredField("mPopup"); | |
popupField.setAccessible(true); | |
Object popup = popupField.get((ListPopupWindow) listPopup); | |
if (popup instanceof PopupWindow) { | |
((PopupWindow) popup).setFocusable(false); | |
} | |
} | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.widget.ListPopupWindow | |
import android.widget.PopupWindow | |
import android.widget.Spinner | |
fun Spinner.avoidDropdownFocus() { | |
try { | |
val listPopup = Spinner::class.java | |
.getDeclaredField("mPopup") | |
.apply { isAccessible = true } | |
.get(this) | |
if (listPopup is ListPopupWindow) { | |
val popup = ListPopupWindow::class.java | |
.getDeclaredField("mPopup") | |
.apply { isAccessible = true } | |
.get(listPopup) | |
if (popup is PopupWindow) { | |
popup.isFocusable = false | |
} | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} |
Thanks for nice solution!
It's working nice, but with setting it to non focusable, it loses the click outside to close functionality. Unfortunately I can't find any workaround, and I tried many.
isOutsideTouchable = true
works for me fwiw
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
apparently this breaks my espresso test, not sure why. It still works with manual pressing the item though.