ListPopupWindow not obeying WRAP_CONTENT width spec

前端 未结 9 1712
执念已碎
执念已碎 2021-02-02 07:12

I\'m trying to use ListPopupWindow to show a list of strings via an ArrayAdapter (eventually this will be a more complex custom adapter). Code is below. As shown in

9条回答
  •  耶瑟儿~
    2021-02-02 07:43

    You could measure the width of the adapter content:

    private int measureContentWidth(ListAdapter listAdapter) {
        ViewGroup mMeasureParent = null;
        int maxWidth = 0;
        View itemView = null;
        int itemType = 0;
    
        final ListAdapter adapter = listAdapter;
        final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            final int positionType = adapter.getItemViewType(i);
            if (positionType != itemType) {
                itemType = positionType;
                itemView = null;
            }
    
            if (mMeasureParent == null) {
                mMeasureParent = new FrameLayout(mContext);
            }
    
            itemView = adapter.getView(i, itemView, mMeasureParent);
            itemView.measure(widthMeasureSpec, heightMeasureSpec);
    
            final int itemWidth = itemView.getMeasuredWidth();
    
            if (itemWidth > maxWidth) {
                maxWidth = itemWidth;
            }
        }
    
        return maxWidth;
    }
    

    and in your showPopup() function:

     ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, STRINGS);
        popup.setAdapter(arrayAdapter);
        popup.setAnchorView(anchorView);
        popup.setContentWidth(measureContentWidth(arrayAdapter));
    

提交回复
热议问题