在ExpandableListAdapter的函数getChild()
和getGroup()
getChildrenCount()
添加Log
结果没有打出
而getChildId()
与getChildView()
getGroupId() getGroupView() getGroupCount()
都被调用 并打出了log
想问问未打出log的3个函数分别在什么时候进行调用以及没有打log的原因
黄舟2017-04-17 14:45:50
點擊展開GroupItem時,getChildrenCount()
被調到,以返回這個Group的child數量(為避免出現數組越界的錯誤);然後adapter才會去調用getChildView()
。
@Override
public int getChildrenCount(int groupPosition) {
Log.d(TAG, "getChildrenCount: groupPosition " + groupPosition);
return count;
}
我們需要覆寫getChildView()
,以填充視圖,那麼首先要拿到數據,而getChild()
的目的就是拿到儲存在adapter中對應位置的數據。
當然,如果你在adapter之外維護了一個child data list,也可以直接從這個list中取資料。
但是getChild()
看起來不是更清楚明了嗎? getGroup()
也是同樣的道理,在執行getGroupView()
填滿group視圖時,讓你可以輕鬆地取得對應的資料。
private List mChildItems;
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Log.d(TAG, " getChildView: groupPosition" + groupPosition + ", childPosition " + childPosition);
// 可以这样:
HashMap<String, String> child = (HashMap<String, String>)getChild(groupPosition, childPosition);
Log.d(TAG, " child data from getChild():" + child.get("Sub Item"));
// 也可以这样:
Log.d(TAG, " child data from my list:" + ((List)mChildItems.get(groupPosition)).get(childPosition));
return view;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
Log.d(TAG, " getChild: groupPosition" + groupPosition + ", childPosition " + childPosition);
return super.getChild(groupPosition, childPosition);
}
部分方法呼叫的Log:
11-05 12:37:50.322: D/Exp(24030): getChildrenCount: groupPosition 1
11-05 12:37:50.325: D/Exp(24030): getChildView: groupPosition1, childPosition 0
11-05 12:37:50.325: D/Exp(24030): getChild: groupPosition1, childPosition 0
11-05 12:37:50.326: D/Exp(24030): child data from getChild():Sub Item 0
11-05 12:37:50.326: D/Exp(24030): child data from my list:{Sub Item=Sub Item 0}
11-05 12:37:50.329: D/Exp(24030): getChildView: groupPosition1, childPosition 1
11-05 12:37:50.329: D/Exp(24030): getChild: groupPosition1, childPosition 1
11-05 12:37:50.329: D/Exp(24030): child data from getChild():Sub Item 1
11-05 12:37:50.329: D/Exp(24030): child data from my list:{Sub Item=Sub Item 1}
11-05 12:37:50.331: D/Exp(24030): getChildView: groupPosition1, childPosition 2
11-05 12:37:50.331: D/Exp(24030): getChild: groupPosition1, childPosition 2
11-05 12:37:50.331: D/Exp(24030): child data from getChild():Sub Item 2
11-05 12:37:50.331: D/Exp(24030): child data from my list:{Sub Item=Sub Item 2}
getChild(), getGroup()
和 android.widget.Adapter 的 Object getItem(int position)
是一回事:『Get the data item associated with the specified position in the data set.’參考:
為了回答這個問題找到的一個project: Expandable ListView in ANDROID
這個答案非常棒 stackoverflow - What is the intent of the methods getItem and getItemId in the Android class BaseAdapter?
android.widget.ExpandableListAdapter 原始碼連結
stackoverflow - Android ExpandableListView - Looking for a tutorial