Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the height of Spinner drop down view in Android

Please suggest any approach which i use to create it .

Query : I am creating 2-Spinner view , where i have to add Country/Cities list , So like if i am selecting india then i am getting 50 items inside the drop down view , problem with this is that it is taking the whole page in height .

What i want : I want to create a drop down view , where user can see only 10 items in the drop down view , other items will be shown whenever user will scroll the drop down view .


My problem

like image 827
Tushar Pandey Avatar asked Dec 15 '13 17:12

Tushar Pandey


3 Answers

You can use Reflection.

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

        // Get private mPopup member variable and try cast to ListPopupWindow
        android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(spinner);

        // Set popupWindow height to 500px
        popupWindow.setHeight(500);
    }
    catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
        // silently fail...
    }
like image 89
shlee1 Avatar answered Oct 21 '22 11:10

shlee1


You can also affect drop down view location and size by subclassing Spinner and overriding its getWindowVisibleDisplayFrame(Rect outRect) which is used by android.widget.PopupWindow for calculations. Just set outRect to limit the area where drop down view can be displayed.

This approach is of course not suitable for all scenarios since sometimes you want to place drop down view so it doesn't obscure another view or by some other condition known only "outside the instance".

In my case, I needed to apply FLAG_LAYOUT_NO_LIMITS flag to my activity window which caused the outRect to be huge and therefore part of the drop down view got sometimes hidden behind navigation bar. In order to restore original behavior I used the following override:

@Override
public void getWindowVisibleDisplayFrame(Rect outRect) {
    WindowManager wm = (WindowManager) getContext.getSystemService(Context.WINDOW_SERVICE);
    Display d = wm.getDefaultDisplay();
    d.getRectSize(outRect);
    outRect.set(outRect.left, <STATUS BAR HEIGHT>, outRect.right, outRect.bottom);
}
like image 9
Almighty Avatar answered Oct 21 '22 13:10

Almighty


As of year 2021 I would go with: Exposed Dropdown Menus and use inside AutoCompleteTextView the following:

android:dropDownHeight="300dp"

If you don't know what is this all about start exploring: Menu-Display & Menu-Documentation

like image 8
F.Mysir Avatar answered Oct 21 '22 13:10

F.Mysir