在RecyclerView顶部添加项目

17

我在我的活动中有一个Recyclerview。当我下拉它时,它会加载新的项目到可回收视图中。 现在我需要将下拉刷新的概念实现到我的Recyclerview中。我已经做到了。但是当我调用下拉刷新时,我得到了新的项目并添加到可回收视图的底部。我需要将新加载的项目添加到可回收视图的顶部位置。如何将新加载的项目添加到Recycler View的顶部位置。

 public void refreshing() throws IllegalStateException{

    new AsyncTask<String, Void, Void>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(String... arg0) {
                final List<NameValuePair> list = new ArrayList<NameValuePair>();
                list.add(new BasicNameValuePair("id", sPreferences.getString("ID", "")));

                final HttpParams httpParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
                DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
                HttpPost httpPost = new HttpPost(Config.requestpatienthistory);
                httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(list));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {                       
                    HttpResponse response = httpClient.execute(httpPost);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    String json = reader.readLine();


                    JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj.has("control")) {

                        JSONArray feedArray = jsonObj.getJSONArray("control");
                        for (int i = 0; i < feedArray.length(); i++) {
                            JSONObject feedObj = (JSONObject) feedArray.get(i);

                            final Historyitem item = new Historyitem();

                            if (feedObj.has("Reported_Time")) {                                 
                                  item.setReported_Time(feedObj.getString("Reported_Time"));                                
                            }
                            historyitems.add(item);
                        }
                    } else {
                        System.out.println("" + "no patients");
                    }
                } catch (SocketException e) {
                   e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }catch (Exception e) {
                    e.printStackTrace();                    
                }             
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressBar.setVisibility(View.GONE);
            historyadapter = new HistoryRecycleListAdapter(getActivity(), getActivity(), historyitems);
            hisrecyclerview.setAdapter(historyadapter);                                                
        }
    }.execute();
}
10个回答

30

我建议你将下拉刷新得到的项目添加到0位置。

mArrayList.add(position, item);
notifyItemInserted(position); 

我对此非常了解,但我的问题是,当我进行下拉刷新时,接收到的数据可能有两种状态。要么有新项目,这些项目尚不存在于列表中,要么旧项目有一些更新。notifyItemInserted能解决这个问题吗?我很努力地不想使用notifyDatasetChanged();.. - Paul Okeke
@PaulOkeke 这个回答与你的问题无关,最好发表另一个问题并寻求答案! - Lalit Poptani

8
在设置RecyclerView时,请添加以下行:
recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,true));

1
哦,我不知道,但我喜欢它。谢谢。 - chrjs
这个救了我的一天。 - 4xMafole

6

我也需要将项目添加到RecyclerView的前部(和底部),但我需要保持滚动焦点在先前的顶部项目处。

因此,我正在将RecyclerView滚动到先前的顶部项目:

mAdapter.pushFront(items);
mAdapter.notifyItemRangeInserted(0, items.size());
recyclerView.scrollToPosition(items.size() - 1);

有更好的解决方案吗?


4
这里应该是答案,而不是问题! - Amir Latifi

3

使用list.add(0,items);可以将新项添加到RecyclerView的顶部。


3
您可以使用Collections反转整个列表:
Collections.reverse(historyitems);

尝试使用适配器:
adapter.insert(yourItem, 0);

尝试使用列表:

list.add(0,listItem);

我需要将仅新增的项目添加到顶部。 - Arya

3

在RecyclerView中,您还可以设置列表的顺序。您只需将适配器的reverse属性设置为true或false即可。

RecyclerView.LayoutManager layoutManager=newLinearLayoutManager(this,LinearLayoutManager.VERTICAL,true);
recyclerView.setLayoutManager(layoutManager);

设置布局管理器到您的Recyclerview适配器后。 如果您想要在您的RecyclerView上执行删除某个item视图,您还需要添加


layoutManager.setStackFromEnd(true);

3

在 XML 中进行布局,你就不再需要使用 LinearLayoutManager 代码了。

<android.support.v7.widget.RecyclerView
        android:id="@+id/recordItemList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:clipToPadding="false"
        android:scrollbars="none"
        app:layoutManager="LinearLayoutManager"
        app:stackFromEnd="true"
        app:reverseLayout="true"/>

感谢,这些属性起了作用。 - 4xMafole
1
app:stackFromEnd="true"app:reverseLayout="true"起了作用,谢谢! - Sam Chen

2
当您下拉刷新数据时,您可以像这样简单地反转列表:
Collections.reverse(yourModelList);
notifyDataSetChanged();

0

Recycler view与项目排序无关。从上面的代码中,您正在刷新内容并简单地显示从服务器获取的内容。也许从服务器返回的项目按照它们被显示的顺序排列。因此,请检查从服务器获取的顺序。


每次调用此函数时,我都会得到新的值,并将这些值添加到循环视图底部。但是我需要将这些项添加到顶部。例如,当我们向下滚动到“Fb”时,如果有新的新闻,它将显示在列表视图的顶部。就像这样,当我调用此函数时,我需要将新项目添加到回收视图的顶部。 - Arya
在适配器中修改您的添加/追加方法。每当您向集合中添加值时,请按以下方式执行:public void appendData(ArrayList newData){ newData.addAll(origData); origData = newData; notifyDatasetChanged(); } 这样可以确保所有新添加的项目将首先出现,然后是旧项目。 - Neeraj Kumar

0
为了实现完美的控制位置系统,将每个项目的位置添加到ArrayList中。对于新项目,其位置将为0。使用Comparator并使用Collection类对项目进行排序。
 Collections.sort(arrayOfPosts, new SortPostByPosition()); 
 listAdapter.notifyDataSetChanged();

这里是 SortPostByPosition 类,可以比较每个项目的位置。

class SortPostByPosition implements Comparator<TimelineListData> {
    public int compare(TimelineListData a, TimelineListData b) {
        return Integer.compare(a.position, b.position);
        // you can compare by your own complex formula too
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接