我不完全确定您的问题是什么意思,但如果您想要动态加载 BaseExpandableListAdapter 中的子项,例如当您单击相关组标题时加载“子项”(如下所示),我有一个解决方案。
v 组标题 1
| -- 子项 1
| -- 子项目 2
v 组标题 2
| -- 子项 1
| -- 子项目 2
在您的 Activity 中,像这样找到您的 ExpandableListView:
ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandable_list_view);
然后添加一个监听器来检查群组点击:
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()
{
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id)
{
if (expandableListView.isGroupExpanded(groupPosition))
expandableListView.collapseGroup(groupPosition);
else
new BackgroundTask(groupPosition).execute();
return true;
}
});
返回 true 将“消耗”单击并在单击时停止组的默认扩展。这就是为什么在您的 ASyncTask 中,您需要手动展开它。如果返回 false,列表视图将在 GUI 中自动展开,并且在您折叠并重新展开组之前,您不会看到后台计算的结果。
在我的代码中,我有一个 SparseBooleanArray 来跟踪是否已经为给定组设置了数据,并且我在 onGroupClick() 方法中检查了该值;我这样做是为了在扩展组时只需要加载一次数据,但显然,如果您希望数据在每次扩展时都更改,那么您不希望这样做。您的问题比较模糊,所以我不确定您使用的确切场景是什么。
private class BackgroundTask extends AsyncTask<Void, Void, List<ReturnType>>
{
int groupPosition;
private BackgroundTask(int groupPosition)
{
this.groupPosition = groupPosition;
}
@Override
protected List<ReturnType> doInBackground(String... params)
{
// TODO: Do your background computation...
// Then return it
}
@Override
protected void onPostExecute(List<ReturnType> resultsList)
{
super.onPostExecute(resultsList);
// TODO: Add the resultsList to whatever structure you're using to store the data in the ListView Adapter
expandableListView.expandGroup(groupPosition);
}
}
我不确定这是否是最好的方法,但它确实对我有用。