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>
  • 相关阅读:
    hdu 4612 Warm up 桥缩点
    树上的一个题目
    2013 ACM/ICPC Asia Regional Online —— Warmup2
    hdu 3308 LCIS 线段树
    最近计划
    hdu 2121 , hdu 4009 无定根最小树形图
    POJ 3164 Command Network 最小树形图模板
    过滤器和拦截器
    struts中的请求数据自动封装
    struts中获取域
  • 原文地址:https://www.cnblogs.com/androidez/p/2979468.html
Copyright © 2011-2022 走看看