zoukankan      html  css  js  c++  java
  • 有关Android ListView根据项数的大小自动改变高度问题

    第一种:按照listview的项数确定高度

     1     ListAdapter listAdapter = listView.getAdapter();  
     2     if (listAdapter == null) { 
     3         return; 
     4     } 
     5 
     6     int totalHeight = 0; 
     7     for (int i = 0; i < listAdapter.getCount(); i++) { 
     8         View listItem = listAdapter.getView(i, null, listView); 
     9         listItem.measure(0, 0); 
    10         totalHeight += listItem.getMeasuredHeight(); 
    11     } 
    12 
    13     ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    14     params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() – 1)); 
    15     ((MarginLayoutParams)params).setMargins(10, 10, 10, 10);
    16     listView.setLayoutParams(params); 

    还有子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常。

    第二种:直接使用当前界面尺寸,稍加调整

    1 ViewGroup.LayoutParams params = listView.getLayoutParams();
    2 params.height = getWindowManager().getDefaultDisplay().getHeight() – 30;
    3 // Toast.makeText(this, params.height+"", 3000).show();
    4 listView.setLayoutParams(params);
    XML布局写法,请注意这里需要一个内部LinerLayout
     1 <ScrollView
     2         android:layout_width="fill_parent"
     3         android:layout_height="fill_parent"
     4         android:fadingEdge = "none"
     5         android:background="#FFF4F4F4"
     6         xmlns:android="http://schemas.android.com/apk/res/android"
     7         >
     8    <LinearLayout
     9     android:gravity="center_horizontal"
    10     android:orientation="vertical"
    11     android:background="#fff4f4f4"
    12     android:layout_width="fill_parent"
    13     android:layout_height="fill_parent"
    14     >
    15     <ListView
    16         android:id="@+id/moreItemsListView"
    17         android:layout_width="fill_parent"
    18         android:layout_height="fill_parent"
    19         android:cacheColorHint="#FFF4F4F4"
    20         android:dividerHeight="0.0dip"
    21         android:fadingEdge="none"
    22         />
    23    </LinearLayout>
    24 </ScrollView>
  • 相关阅读:
    leetcode Super Ugly Number
    leetcode Find Median from Data Stream
    leetcode Remove Invalid Parentheses
    leetcode Range Sum Query
    leetcode Range Sum Query
    leetcode Minimum Height Trees
    hdu 3836 Equivalent Sets
    hdu 1269 迷宫城堡
    hud 2586 How far away ?
    poj 1330 Nearest Common Ancestors
  • 原文地址:https://www.cnblogs.com/androidez/p/2979468.html
Copyright © 2011-2022 走看看