滚动加载更多recycleview时设置最后位置

时间:2016-03-17 08:16:07

标签: android android-studio

我正在尝试加载更多recycleview它工作正常但当滚动recycleview当时总是第一项是视图的顶部,我想在顶部的下一个可滚动项目,我该如何解决这个问题,请帮助我< / p>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private int page_no = 0;
    private RecyclerView mRecyclerView;
    private ArrayList<NotificationBean> mUsers = new ArrayList<>();
    private UserAdapter mUserAdapter;
    private NotificationBean mNotificationBean;
    private int loadMoreArrayListSize;
    public int arrayListSize;
    // private LinearLayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mUsers = new ArrayList<>();

        mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
//        mLayoutManager = new LinearLayoutManager(this);
//        mRecyclerView.setLayoutManager(mLayoutManager);
        getData(MainActivity.this, page_no, "4");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mUserAdapter = new UserAdapter();
        mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                Log.e("haint", "Load More");
                mUsers.add(null);
                mUserAdapter.notifyItemInserted(mUsers.size() - 1);

                //Load more data for reyclerview
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("haint", "Load More 2");

                        //Remove loading item
                        mUsers.remove(mUsers.size() - 1);
                        mUserAdapter.notifyItemRemoved(mUsers.size());

                        //Load data
                        page_no++;
                        //callAPI(1);
                        //  Log.d("arrTemp Position: : ", String.valueOf(arrTemp));
                        getData(MainActivity.this, page_no, "4");
                        // mLayoutManager.scrollToPositionWithOffset(mUsers.size() - 10, 0);
                        Log.v("LoadMoreListener arsize", Integer.toString(mUsers.size()));
                        loadMoreArrayListSize = arrayListSize - mUsers.size();
                        Log.v("loadMoreArrayListSize", Integer.toString(loadMoreArrayListSize));

                    }
                }, 5000);
            }
        });
    }

    static class UserViewHolder extends RecyclerView.ViewHolder {
        public ImageView imgView;
        public TextView txtComment, txtParamLink, txtTitle, txtVideoId;

        public UserViewHolder(View itemView) {
            super(itemView);
            txtComment = (TextView) itemView.findViewById(R.id.txtComment);
            txtParamLink = (TextView) itemView.findViewById(R.id.txtParamLink);
            txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            txtVideoId = (TextView) itemView.findViewById(R.id.txtVideoId);
            imgView = (ImageView) itemView.findViewById(R.id.imgView);
        }
    }

    static class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
        }
    }

    class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final int VIEW_TYPE_ITEM = 0;
        private final int VIEW_TYPE_LOADING = 1;

        private OnLoadMoreListener mOnLoadMoreListener;

        private boolean isLoading;
        private int visibleThreshold = 5;
        private int lastVisibleItem, totalItemCount;

        public UserAdapter() {
            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                    if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                        if (mOnLoadMoreListener != null) {
                            mOnLoadMoreListener.onLoadMore();
                        }
                        isLoading = true;
                    }
                }
            });
        }

        public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
            this.mOnLoadMoreListener = mOnLoadMoreListener;
        }

        @Override
        public int getItemViewType(int position) {
            return mUsers.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == VIEW_TYPE_ITEM) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.notification_item, parent, false);
                return new UserViewHolder(view);
            } else if (viewType == VIEW_TYPE_LOADING) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_loading_item, parent, false);
                return new LoadingViewHolder(view);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof UserViewHolder) {
                NotificationBean user = mUsers.get(position);
                UserViewHolder userViewHolder = (UserViewHolder) holder;
//                userViewHolder.tvName.setText(user.getName());
//                userViewHolder.tvEmailId.setText(user.getEmail());
                userViewHolder.txtComment.setText(Integer.toString(user.getComment()));
                userViewHolder.txtParamLink.setText(user.getPermalink());
                userViewHolder.txtTitle.setText(user.getTitle());
                userViewHolder.txtVideoId.setText(user.getVideoid());
                if (user.getImage() != null) {
                    Glide.with(MainActivity.this).load(user.getImage()).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).dontAnimate().into(userViewHolder.imgView);
                }
            } else if (holder instanceof LoadingViewHolder) {
                LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
                loadingViewHolder.progressBar.setIndeterminate(true);
            }
        }

        @Override
        public int getItemCount() {
            return mUsers == null ? 0 : mUsers.size();
        }

        public void setLoaded() {
            isLoading = false;
        }
    }

    private void getData(Context context, final int posts_per_page, final String type) {

//        final ProgressDialog pDialog = new ProgressDialog(this);
//        pDialog.setMessage("Loading...");
//        pDialog.show();
        RequestQueue queue = Volley.newRequestQueue(context);
//        StringRequest sr = new StringRequest(Request.Method.POST, "http://asiatube.info/sgtube/api/ws.php", new Response.Listener<String>() {
        StringRequest sr = new StringRequest(Request.Method.POST, "http://steanrewards.com/api/ws.php", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                JSONArray jArray;
                JSONArray jsonArray = null;
                JSONObject jsonObject = null;
                try {
                    jArray = new JSONArray(response);
                    JSONObject jObj = jArray.getJSONObject(0);
                    int code = jObj.getInt("code");
                    if (code == 0) {
                        Log.d("allcount:: :: ::", String.valueOf(jObj.optInt("allcount")));
                        if (jObj.has("result")) {
                            jsonArray = jObj.getJSONArray("result");
                            Log.d("EVENTLIST ARRAY=", jsonArray.length() + "");

                            if (jsonArray != null && jsonArray.length() > 0) {

//                                arrTemp = new ArrayList<>();
                                for (int i = 0; i < jsonArray.length(); i++) {

                                    jsonObject = jsonArray.getJSONObject(i);
                                    mNotificationBean = new NotificationBean();
                                    mNotificationBean.id = jsonObject.getString("id");
                                    mNotificationBean.permalink = jsonObject.getString("permalink");
                                    mNotificationBean.image = jsonObject.getString("image");
                                    mNotificationBean.title = jsonObject.getString("title");
                                    mNotificationBean.videotype = jsonObject.getString("videotype");
                                    mNotificationBean.videoid = jsonObject.getString("videoid");
                                    mNotificationBean.desc = jsonObject.getString("desc");
                                    mNotificationBean.author_url = jsonObject.getString("author_url");
                                    mNotificationBean.like = jsonObject.getString("like");
                                    mNotificationBean.unlike = jsonObject.getString("unlike");
                                    mNotificationBean.comment = jsonObject.getInt("comment");
                                    //arrTemp.add(mNotificationBean);
                                    mUsers.add(mNotificationBean);
                                    Log.v("ArrayList Size:: :: ", Integer.toString(mUsers.size()));
                                    mRecyclerView.setAdapter(mUserAdapter);
                                    mUserAdapter.notifyDataSetChanged();
                                    mUserAdapter.setLoaded();

                                }
                                Log.v("mUsers Size:: :: ", Integer.toString(mUsers.size()));
                                arrayListSize = mUsers.size();
                            }
                            //mAdapter.notifyDataSetChanged();
//                                    mAdapter = new NotificationAdapter(mArrayList);
                            // pDialog.dismiss();
                        }
                    } else {
                        // pDialog.dismiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Check internet connection", Toast.LENGTH_LONG).show();
            }
        }) {

            @Override

            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("posts_per_page", Integer.toString(posts_per_page));
                params.put("type", type);
//                params.put("fromsite", fromsite);
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        sr.setRetryPolicy(new DefaultRetryPolicy(
                15000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        queue.add(sr);

    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp" />
</LinearLayout>

2 个答案:

答案 0 :(得分:0)

加载时,您必须知道新加载项目的顶部元素的位置。只需致电:

recyclerView.scrollToPosition(position);

只要您想在当前视图中显示特定项目,就可以使用它,只需使用列表位置调用此函数即可。例如,您在每80个项目后加载新项目,因此新加载项目的位置将为80,因此您可以致电:

recyclerView.scrollToPosition(80);

在加载越来越多的项目时,请继续更新此位置。

答案 1 :(得分:0)

虽然recyclerView.scrollToPosition(position);快速解决方法我建议您不要使用,但是当你再次setAdapter()时会发生这种情况在分页后,您需要在获得新数据后调用notifyDataSetChanged