ListPopupWindow not obeying WRAP_CONTENT width spec

前端 未结 9 1521
执念已碎
执念已碎 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<String>(this, android.R.layout.simple_list_item_1, STRINGS);
        popup.setAdapter(arrayAdapter);
        popup.setAnchorView(anchorView);
        popup.setContentWidth(measureContentWidth(arrayAdapter));
    
    0 讨论(0)
  • 2021-02-02 07:45

    The following can help;

    listPopupWindow.setWidth(400);
    listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
    
    0 讨论(0)
  • 2021-02-02 07:48

    The problem is with the implementation of ListPopupWindow. I checked the source code, and using setContentWidth(ListPopupWindow.WRAP_CONTENT) or setWidth(ListPopupWindow.WRAP_CONTENT) makes the popup window use the width of its anchor view instead.

    0 讨论(0)
提交回复
热议问题