2016-09-23 79 views
0

我想要計算可展開列表視圖的高度,以便我可以顯示包含標題的所有項目,以便用戶不必滾動以查看內容。計算高度的問題ExpandableListView

這是我顯示listview的片段。在它旁邊是一個日曆:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/scrollLayout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fillViewport="true" 
android:orientation="vertical"> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".fragments.DashboardFragment"> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     tools:context=".fragments.DashboardFragment"> 
     <ExpandableListView 
      android:id="@+id/lvExp" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 
     <CalendarView 
      android:id="@+id/calendarView" 
      android:layout_width="match_parent" 
      android:layout_height="292dp" /> 
    </LinearLayout> 
</LinearLayout> 

我計算在位於片段setOnGroupExpandListener高度。首先,我得到兩個孩子的身高爲頭:

height += ((expListView.getChildAt(0).getHeight()+expListView.getDividerHeight())-expListView.getDividerHeight())*listAdapter.getGroupCount(); 

然後我計算兒童使用下一個公式高度:

for (int i = 0; i < listAdapter.getGroupCount();i++){ 
if (expListView.isGroupExpanded(i)){   
    height += listAdapter.getChildrenCount(i)*(expListView.getChildAt(0).getHeight()+expListView.getDividerHeight())-expListView.getDividerHeight();   
} 
} 

當我展開第一組間隙放置在列表視圖和日曆之間。當我展開第二組時,他們之間會有更大的差距。

我已經有了相同的公式來摺疊它們。

我應該用另一個公式來計算高度嗎?

All items collapsed

First item expanded

All items expanded

回答

1

你不應該在所有這樣做。列表視圖的要點是滾動。如果你不想滾動,只需將它作爲視圖添加到LinearLayout。

至於你的算法 - 它不會工作。 ListView不知道任何項目的高度,除非它們當前在屏幕上。所以它實際上不可能計算這個。

此外,你在做什麼不會計算所有視圖的高度 - 列表視圖只有子項的屏幕上的項目。他們回收這些項目之間的項目。所以你的算法只能得到當前屏幕上物品的高度。

+0

問題是我需要顯示一個項目列表,它必須展開/摺疊,我找到的唯一解決方案是使用可展開的列表視圖。如果你知道另一個解決方案,我將非常感謝 – n4h1n

+0

可擴展列表視圖對此很有幫助 - 只要你想(或者至少不介意)滾動。如果你不想滾動,那麼你不想使用任何形式的列表視圖。在那個時候寫下你自己的觀點。雖然看你的例子 - 我認爲滾動是完全合適的。 –