2012-09-27 48 views
1

要增加的ListView的高度,我使用的ListView exbandable作爲,如何動態擴展ListView的高度android?

public class ExpandableListView extends ListView { 

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

    public ExpandableListView(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); 
      System.out.println("params h "+params.height+" "+params); 
      setLayoutParams(params); 
     } 

     super.onDraw(canvas); 
    } 

} 

layout.xml如,

<com.jems.realtimedata.ExpandableListView 
       android:id="@+id/listView1" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"  
       android:layout_marginLeft="10dp" 
       android:layout_marginRight="10dp" 
       android:layout_marginTop="25dp" 
       android:background="@color/list_back" 
       android:cacheColorHint="#00000000" 
       android:divider="@drawable/line" 
       android:paddingLeft="7dp" 
       android:paddingRight="7dp" 
       android:paddingTop="10dp" 
       android:scrollbars="none" /> 

但是,列表的最後一項顯示不正常。我也使用了實用工具類,但沒有改變list.Any其他解決方案來擴展視圖。請幫我解決這個問題。

回答

2

變線

params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0); 

這樣:

params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() + 1 : 0); 

這隻適用於包含單行項目的列表。