Limit height of ListView on Android
I solved this problem in code, setting height of listview only if it has more than 5 items in it:
if(adapter.getCount() > 5){
View item = adapter.getView(0, null, listView);
item.measure(0, 0);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, (int) (5.5 * item.getMeasuredHeight()));
listView.setLayoutParams(params);
}
Notice that I set the max height to 5.5 times the height of a single item, so the user will know for sure there is some scrolling to do! :)
I had this exact issue and to solve it I created two seperate LinearLayouts
to house the ListView
and Button
respectively. From there I put both in another Linear Layout
and set that container's android:orientation
to vertical
. I also set the weight of the the LinearLayout
that housed the ListView
to 0.1
but I dont know if that has any effect. From there, you can set the height of the bottom container (that has your button) to whatever height you would like.
EDIT this is what i mean:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:orientation="horizontal">
<ListView
android:id="@+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="2px"></ListView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="45px"
android:background="@drawable/drawable"
android:orientation="horizontal">
<Button
android:id="@+id/moreButton"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="@drawable/btn_more2"
android:paddingRight="20px" />
</LinearLayout>
The above solution will fix the button the the bottom of the screen.
To have the button float at the bottom of the list, change the height of ListView01
to wrap_content
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:orientation="horizontal">
<ListView
android:id="@+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="2px"></ListView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="45px"
android:background="@drawable/drawable"
android:orientation="horizontal">
<Button
android:id="@+id/moreButton"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="@drawable/btn_more2"
android:paddingRight="20px" />
</LinearLayout>