android - 在 ListView 顶部添加新项目不起作用。将项目添加到底部

标签 android android-listview android-asynctask

我在将 ListView 中添加的新项目显示在 ListView 的顶部时遇到一些困难。但是,当新项目添加到 ListView 时,我希望当前项目保持可见,并将新项目添加到其上方。

为此,我按照此处的解决方案进行操作:https://stackoverflow.com/a/3035521/450534当这也不起作用时,我开始进行一些尝试。

还值得一提的是,我正在使用 Chris Banes 的 Pull to Refresh 库。

现在奇怪的是,当我在 ListView 中最后一项下面添加分页数据时,一切都运行良好。但我很困惑为什么新项目不会放置在当前项目之上并保持当前位置。这就是我到目前为止所做的(在 onPostExecute() 中):

// GET THE CURRENT LISTVIEW POSITION (USED TO MAINTAIN SCROLL POSITION)
int currentPosition = actualListView.getFirstVisiblePosition();
Log.e("POSITION", String.valueOf(currentPosition));

View v = actualListView.getChildAt(0);

int top = (v == null) ? 0 : v.getTop();
Log.e("TOP", String.valueOf(top));

/*****  APPEND NEW DATA TO THE ADAPTER AND THE LISTVIEW     *****/
// CAST THE ADAPTER (AGAIN)
adapter = new NewsFeedAdapter(getActivity(), arrFeeds);

// SET THE ADAPTER TO THE LISTVIEW
actualListView.setAdapter(adapter);

// SET THE SCROLL POSITION
actualListView.setSelectionFromTop(currentPosition, top);

lv.onRefreshComplete();

这是ListView的开始,这是在顶部(上面)添加新项目后仍然应该看到的内容。我计划展示一个小布局,显示顶部有多少个新提要。就像 Facebook 应用程序现在所做的那样。

Start Of the ListView

但是新项目会添加到 ListView 的底部,而不是现有项目的顶部。

New items are added to the bottom of the ListView

有什么明显的事情我错过了吗?如果您需要我添加更多代码,请告诉我,我会立即添加。

最佳答案

另一种替代方法是将项目添加到用于填充适配器的 ArrayList 的 0 位置。

  your_array_list.add(int index, Object element) //Inserts the specified element at the specified position in this list.

添加后,您可以在 listAdapter 上调用 notificationDataSetChanged()。

请确认是否有效..

关于android - 在 ListView 顶部添加新项目不起作用。将项目添加到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459305/

相关文章:

java - 具有特定 Product Flavors 依赖性的 android-library

android - Android 上的 SOAP Web 服务

Android:带有复选框问题的 ListView

android - 如果已经设置,如何避免设置 firestore 文档字段

android进度对话框背景颜色

android - 如何从 ArrayList<HashMap<String,String>> 和 Android 中的 ListView 行中删除值?

java - 如何在 ListView 中搜索有关使用 fragment 布局的信息

java - 异步任务 : Implementing executeOnExecutor() thread class in AudioTrack

android - AsyncTask 和 Looper.prepare() 错误

java - ASyncTask 导致 getDatabaseLocked