Android limit the no of items displayed in a spinner's dropdown list

后端 未结 3 713
感动是毒
感动是毒 2020-12-01 21:34

I have a spinner item bound to an array adapter which might have 0 or more items at any time. I want the spinner dropdown list to only show three items at a time, the rest o

3条回答
  •  遥遥无期
    2020-12-01 22:02

    The recommended solutions are not really interesting because they hard code the height of drop down this is bad because font size are actually different in different phones, I handled it dynamic and reliable like this :

    ArrayAdapter adapter = new ArrayAdapter(this,
                    R.layout.drop_down_text_view,
                    new String[]{"A", "B", "C", "D", "E"}) {
    
                @NonNull
                @Override
                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    TextView dropDownTextView = (TextView) super.getView(position, convertView, parent);
    
                    dropDownTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            myDropDownMenuOrSpinnerOrAutoCompleteTextView.setDropDownHeight(dropDownTextView.getHeight() * 3);
    
                            dropDownTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });
                    return dropDownTextView;
                }
            };
    

提交回复
热议问题