Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ListView height to display all available items

I have a ListView inside a ScrollView.

How can I set the height of the ListView so that all the items in its adapter fit in it and it does not need to scroll.

like image 282
mustafa Avatar asked Nov 27 '15 16:11

mustafa


2 Answers

If you want a list of items that doesn't scroll, it's called a linearlayout.

Else if you want you can custom listview as:

public class NonScrollListView extends ListView {

    public NonScrollListView(Context context) {
        super(context);
    }
    public NonScrollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();    
    }
}
like image 129
mdtuyen Avatar answered Nov 03 '22 22:11

mdtuyen


You can use something like this, it will expand the list so it won't need scrolling. Just remember to wrap it in your XML with a ScrollView:

<ScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

and the class:

public class ExpandedListView extends ListView {

private android.view.ViewGroup.LayoutParams params;
private int old_count = 0;

public ExpandedListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    if (getCount() != old_count) {
        old_count = getCount();
        params = getLayoutParams();
        params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);
        setLayoutParams(params);
    }

    super.onDraw(canvas);
}
}

You can also refer to this question which will be helpful: Calculate the size of a list view or how to tell it to fully expand

like image 1
Udi Idan Avatar answered Nov 04 '22 00:11

Udi Idan