简体   繁体   English

将项目添加到 recyclerview 的顶部

[英]Add Items to top of recyclerview

I have a Recyclerview in my activity.我的活动中有一个 Recyclerview。 when I pull down it will load new items to recycle view.当我下拉时,它会加载新项目以回收视图。 Now I need to implement pull to refresh the concept to my recyclerview.现在我需要实现 pull 来刷新我的 recyclerview 的概念。 I have done that.我已经这样做了。 But when I call pull to refresh I am getting new items and added to recycle view bottom.但是当我调用 pull 刷新时,我得到了新项目并添加到回收视图底部。 I required to add new items to top of my recycle view.我需要在回收视图的顶部添加新项目。 How can I add new loaded items to the top position of 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();
}

I would insist you to add item at 0th position which is coming from pull to refresh as below,我会坚持你在0th位置添加项目,它来自下拉刷新,如下所示,

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

I also need to add items to the front of recyclerview(and to bottom), but i need to keep scroll focused at the previous top item.我还需要将项目添加到 recyclerview 的前面(和底部),但我需要将滚动焦点保持在前一个顶部项目上。

So i'm scrolling recyclerview to previous top item:所以我将 recyclerview 滚动到上一个顶部项目:

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

Is there a better solution?有更好的解决方案吗?

设置 recyclerview 时添加以下行

recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,true));

You can reverse your whole list using Collections :您可以使用 Collections 反转整个列表:

Collections.reverse(historyitems);

Try using adapter :尝试使用适配器:

adapter.insert(yourItem, 0);

Try using List :尝试使用列表:

list.add(0,listItem);

in Recyclerview you also set your list order.在 Recyclerview 中,您还可以设置列表顺序。 you just set your adapter to reverse true or false.您只需将适配器设置为反转 true 或 false。

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

after set layout manager to your Recyclerview Adapter.将布局管理器设置为 Recyclerview Adapter 后。 And if you want to perform delete some item view on your recyclerview also you need to add如果你想在你的 recyclerview 上执行删除一些项目视图,你还需要添加

layoutManager.setStackFromEnd(true);

use list.add(0,items);使用list.add(0,items); it will add new item to top of recyclerview它将在 recyclerview 顶部添加新项目

Do it in xml you don't need LinearLayoutManager code anymore在 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"/>

Recycler view has nothing to with ordering of items.回收者视图与物品的排序无关。 From the above code you are refreshing contents and simply displaying what you are getting from server.从上面的代码中,您正在刷新内容并简单地显示您从服务器获得的内容。 May be the items returned from server are in the order they get displayed.可能是从服务器返回的项目按它们显示的顺序排列。 So check the order from server what you are getting.因此,请检查您从服务器获得的订单。

For perfect control position system, add each item's position in arraylist.为了完美的控制位置系统,在arraylist中添加每个项目的位置 For new item position will be 0. Use Comparator and sort items by using Collection Class.新项目的位置将为 0。使用 Comparator 并使用 Collection Class 对项目进行排序。

 Collections.sort(arrayOfPosts, new SortPostByPosition()); 
 listAdapter.notifyDataSetChanged();

Here is SortPostByPosition class that compare position of each item.这是比较每个项目位置的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
    }
}

When you pull to refresh your data then you can simply reverse your list like this:当您拉动刷新数据时,您可以简单地反转您的列表,如下所示:

Collections.reverse(yourModelList);
notifyDataSetChanged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM