2016-05-17 24 views
1

Activity中,如何獲得第一組視圖Expandable ListView獲取第一組Expandable ListView視圖的句柄

下面是我在做什麼:

public int getFirstVisibleGroup() { 
     LogUtil.i(TAG, "getFirstVisibleGroup called"); 
     int firstVis = listView.getFirstVisiblePosition(); 
     LogUtil.i(TAG, "firstVis = " + firstVis); 
     long packedPosition = listView.getExpandableListPosition(firstVis); 
     LogUtil.i(TAG, "packedPosition = " + packedPosition); 
     LogUtil.i(TAG, "firstVisibleGroup = " + ExpandableListView.getPackedPositionGroup(packedPosition)); 
     return ExpandableListView.getPackedPositionGroup(packedPosition); 
    } 

    public View getGroupView(ExpandableListView listView, int groupPosition) { 
     LogUtil.i(TAG, "getGroupView called"); 
     int flatPosition = listView.getFlatListPosition(groupPosition); 
     LogUtil.i(TAG, "flatPosition = " + flatPosition); 
     int first = getFirstVisibleGroup(); 
     LogUtil.i(TAG, "first = " + first); 
     LogUtil.i(TAG, "returning child at position " + (flatPosition - first)); 
     return listView.getChildAt(flatPosition - first); 
    } 

而且我把它叫做:

View view = getGroupView(listView, 0); 

最終成爲listView.getChildAt(0)。並且返回的view爲空。

什麼是正確的做法?

+0

你什麼時候試圖調用'listView.getChildAt(0)'?那是在onCreate/onResume之間還是在用戶點擊視圖之後? – Budius

+0

@Budius in'onCreate()',我做了一個服務調用,當服務調用的結果到來時,我更新'Expandable ListView',之後我調用上面的方法。 –

回答

1

所有基於適配器的視圖(ListView,GridView,RecyclerView)僅在屏幕上佈置完成後纔將視圖添加到自身。以便他們可以計算適當的大小並查詢足夠的子視圖。

因此,在onCreate期間,您永遠不會有任何意見。這意味着如果您想與其子視圖進行交互,那麼必須稍後再進行。

一個合適的方法是使用OnPreDraw偵聽器。這是在系統調用draw(canvas)之前的觀點。例如:

public MyActivity extends Activity implements ViewTreeObserver.OnPreDrawListener { 

    @Override 
    public void onCreate(bundle){ 
     ... build your layout and your listview 

     // during onCreate you add a PreDrawListener 
     rootView.getViewTreeObserver().addOnPreDrawListener(this); 
    } 

    @Override 
    public void onPreDraw() { 

     ... do your logic here !!! 


     rootView.getViewTreeObserver().removeOnPreDrawListener(this); // remove itself, you only need the fist pass 
     return true; // must return true, or else the system won't draw anything. 
    } 

} 
+0

我仍然將'view'視爲'null'。另外,即使在網絡響應來臨之前,onPreDraw()也會被調用。 –

+0

哦...我想我錯過了你說網絡的地方。但是這個想法是一樣的,它是一個'PreDraw',它會在屏幕上再次繪製之前被調用。這意味着對於你的情況,你應該在調用setAdapter或notifyDataSetChanged後立即調用addOnPreDrawListener。 – Budius

+0

好的。我會嘗試。 –