Android ListView根据项数的大小自动改变高度

 ListAdapter listAdapter = listView.getAdapter();  
    if (listAdapter == null) { 
        return; 
    

    int totalHeight = 0; 
    for (int i = 0; i < listAdapter.getCount(); i++) { 
        View listItem = listAdapter.getView(i, null, listView); 
        listItem.measure(0, 0); 
        totalHeight += listItem.getMeasuredHeight(); 
    

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() – 1)); 
    ((MarginLayoutParams)params).setMargins(10, 10, 10, 10);
    listView.setLayoutParams(params);

 

 

 

setLayoutParams(new LayoutParams(50,android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

posted on 2012-06-18 19:43  jiezzy  阅读(857)  评论(0编辑  收藏  举报