mardi 21 mars 2017

Modifying Android Spinner Dropdown via Reflection - android.widget.Spinner$DropdownPopup cannot be cast to android.support.v7.widget.ListPopupWindow

I have a spinner that I would like the dropdown to always be right-aligned to the spinner itself. I have the following code:

 try {
     Field popup = Spinner.class.getDeclaredField("mPopup");
     popup.setAccessible(true);

     popupWindow = (ListPopupWindow) popup.get(reportList);

     popupWindow.setDropDownGravity(Gravity.END | Gravity.RIGHT);   //requires KitKat or above
     popupWindow.setWidth(measureContentWidth(dataAdapter));
} catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
     Log.e("Exception", e.getMessage());
}

The problem is that setDropDownGravity requires KitKat or above. However, if I change my ListPopupWindow import from android.widget.ListPopupWindow to android.support.v7.widget.ListPopupWindow, I get the following error:

android.widget.Spinner$DropdownPopup cannot be cast to android.support.v7.widget.ListPopupWindow

Is there any way I can set get the dropdown to be right-aligned on devices running Android versions lower than KitKat?





Aucun commentaire:

Enregistrer un commentaire