Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the width of the ListView in a PopupWindow on Android?

I inflated a ListView as the contentView in a PopupWindow. If I don't set the width & height, I can't see the PopupWindow. If I set them like this:

setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

The layout is being set like "fill_parent". Why?

The layout attributes of the ListView and ListView item are all set to "wrap_content". Any suggestion? Thanks.

like image 764
shiami Avatar asked Feb 25 '23 22:02

shiami


2 Answers

This is how to do it:

// Don't use this. It causes ListView's to have strange widths, similar to "fill_parent"
//popupWindow.setWindowLayoutMode(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);

// Instead, use this:
final int NUM_OF_VISIBLE_LIST_ROWS = 4;
listView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popupWindow.setWidth(listView.getMeasuredWidth());
popupWindow.setHeight((listView.getMeasuredHeight() + 10) * NUM_OF_VISIBLE_LIST_ROWS);

Note that setWidth() and setHeight() use raw pixel values, so you need to adjust for different screen sizes and different densities.

like image 175
jimmy Avatar answered Apr 08 '23 00:04

jimmy


My solution is override onMeasure of ListView like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int maxWidth = meathureWidthByChilds() + getPaddingLeft() + getPaddingRight();
    super.onMeasure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY), heightMeasureSpec);     
}

public int meathureWidthByChilds() {
    int maxWidth = 0;
    View view = null;
    for (int i = 0; i < getAdapter().getCount(); i++) {
        view = getAdapter().getView(i, view, this);
        view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        if (view.getMeasuredWidth() > maxWidth){
            maxWidth = view.getMeasuredWidth();
        }
    }
    return maxWidth;
}
like image 29
Fedir Tsapana Avatar answered Apr 08 '23 00:04

Fedir Tsapana