gpt4 book ai didi

android - 如何在 android 中的父项目可扩展 ListView 上动态添加子项目?

转载 作者:行者123 更新时间:2023-11-30 00:54:11 26 4
gpt4 key购买 nike

我正在开发一个包含一个可扩展 ListView 的 Android 应用程序,用于从 Web 服务加载数据,但我不想在启动时加载整个数据,但首先加载父列表,然后单击父列表展开特定列表项 ListView 的子项首先加载特定项的子项是否可能?

谢谢

最佳答案

我不完全确定你的问题是什么意思,但如果你想要的是在 BaseExpandableListAdapter 中动态加载子项,例如单击相关组标题时加载“子项”(如下所示),我有一个解决方案。

v Group header 1| -- Child item 1| -- Child item 2v Group header 2| -- Child item 1| -- Child item 2

In your Activity, find your ExpandableListView like this:

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;
}
});

return true 会“消耗”点击并在点击时停止组的默认展开。这就是为什么在您的 ASyncTask 中,您需要手动展开它。如果您返回 false, ListView 将在 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);
}
}

我不确定这是否是最好的方法,但它确实对我有用。

关于android - 如何在 android 中的父项目可扩展 ListView 上动态添加子项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40447637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com