成功加载下一页后,GridView始终滚动到顶部

时间:2017-09-18 04:07:23

标签: android gridview pagination android-recyclerview

使用recyclerviewrecyclerview时,我遇到了困难。问题是当我的应用程序成功加载下一页(下一个数据)时,package com.putuguna.sitehinduapk.adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.putuguna.sitehinduapk.R; import com.putuguna.sitehinduapk.activities.DetailBlogPostActivity; import com.putuguna.sitehinduapk.models.listposts.ItemPostModel; import com.putuguna.sitehinduapk.utils.GlobalFunction; import com.putuguna.sitehinduapk.utils.GlobalVariable; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class ListPostAdapter extends RecyclerView.Adapter<ListPostAdapter.ViewHolder>{ private List<ItemPostModel> mListPost; private Context mContext; public ListPostAdapter(List<ItemPostModel> mListPost, Context mContext) { this.mListPost = mListPost; this.mContext = mContext; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.adapter_item_list_post, null); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { final ItemPostModel post = mListPost.get(position); List<String> listURL = extractUrls(post.getContentPosting()); Glide.with(mContext) .load(listURL.get(0)) .into(holder.ivImagePost); holder.tvTitle.setText(post.getTitle()); holder.llItemPost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TO DO OnClick } }); List<String> listLabel = post.getListLabel(); String labelPost=""; for(int i=0; i<listLabel.size();i++){ labelPost += "#"+listLabel.get(i) + " "; } holder.tvLabel.setText(labelPost); if ((position >= getItemCount() - 1)) load(); } public abstract void load(); @Override public int getItemCount() { return mListPost.size(); } public static class ViewHolder extends RecyclerView.ViewHolder{ public ImageView ivImagePost; public TextView tvTitle; public LinearLayout llItemPost; public TextView tvLabel; public ViewHolder(View itemView) { super(itemView); ivImagePost = (ImageView) itemView.findViewById(R.id.iv_image_post); tvTitle = (TextView) itemView.findViewById(R.id.tv_blog_title); llItemPost = (LinearLayout) itemView.findViewById(R.id.ll_item_post); tvLabel = (TextView) itemView.findViewById(R.id.textview_label_adapter); } } public static List<String> extractUrls(String input) { List<String> result = new ArrayList<String>(); Pattern pattern = Pattern.compile( "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" + "|mil|biz|info|mobi|name|aero|jobs|museum" + "|travel|[a-z]{2}))(:[\\d]{1,5})?" + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { result.add(matcher.group()); } return result; } } 总是回到顶部。

我想从最后一个索引开始MainActivity.java

示例:第一页加载10项,成功贷款下一页后,回收站视图开始从第8项滚动。

为了解决这个问题,我已经尝试了stackoverflow上的所有解决方案仍然没有得到任何结果。

以下是我的代码:

 private void getListPost(){
        mSwipeRefreshLayout.setRefreshing(true);

        String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);

        BloggerApiService apiService = BloggerApiClient.getClient().create(BloggerApiService.class);
        Call<ListPostModel> call = apiService.getListPost(GlobalVariable.APP_KEY_V3);

        call.enqueue(new Callback<ListPostModel>() {
            @Override
            public void onResponse(Call<ListPostModel> call, Response<ListPostModel> response) {
                ListPostModel listpost = response.body();
                initDataView(listpost);
                mSwipeRefreshLayout.setRefreshing(false);

            }

            @Override
            public void onFailure(Call<ListPostModel> call, Throwable t) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * this method used for post (next page)
     */
    private void getNextListPost(){
        mSwipeRefreshLayout.setRefreshing(true);

        String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
        BloggerApiService apiService = BloggerApiClient.getClient().create(BloggerApiService.class);
        Call<ListPostModel>  call = apiService.getNexPageListPost(GlobalVariable.APP_KEY_V3,nextPageToken);

        call.enqueue(new Callback<ListPostModel>() {
            @Override
            public void onResponse(Call<ListPostModel> call, Response<ListPostModel> response) {
                ListPostModel listpost = response.body();
                initDataView2(listpost);
                mSwipeRefreshLayout.setRefreshing(false);

            }

            @Override
            public void onFailure(Call<ListPostModel> call, Throwable t) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    public void onRefresh() {
        mListPost.clear();
        getListPost();
    }

    private void initDataView(ListPostModel listpost){
        GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
        mListPost.addAll(listpost.getListItemsPost());
        mPostAdapter = new ListPostAdapter(mListPost, this) {
            @Override
            public void load() {
                ItemPostModel item = mListPost.get(mListPost.size()-1);
                getNextListPost();
            }
        };

        mRecyclerviewPost.setAdapter(mPostAdapter);
        //mPostAdapter.notifyDataSetChanged();

        mRecyclerviewPost.setHasFixedSize(true);
        mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
    }


    /**
     * this method used for set view (next page)
     * @param listpost
     */
    private void initDataView2(ListPostModel listpost){
        GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
        final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
        List<ItemPostModel> itemNextPost = listpost.getListItemsPost();
//        itemNextPost.addAll(mListPost);
        mListPost.addAll(itemNextPost);
        mPostAdapter = new ListPostAdapter(mListPost, this) {
            @Override
            public void load() {
                ItemPostModel item = mListPost.get(mListPost.size()-1);
                if(nextPageToken==null){

                }else{
                    getNextListPost();
                }
            }
        };

        mRecyclerviewPost.setAdapter(mPostAdapter);
        mRecyclerviewPost.setHasFixedSize(true);
        mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
an
    }

此代码#include<iostream> #include <string> using namespace std; int charsearch(string searchInto, char ch, int start = 0) { int x = 0; long n = searchInto.length(); for (int i = 1; i < n; i++) { cout << ch; if (searchInto[i] == ch) { i = x; } else i++; } cout<< x; return x; } int substr(string src, string tosearch, int start = 0) { string searchInto = src; long n = searchInto.size(); long m = tosearch.size(); int ans = -1; for (int i = start; i < n; ++i) { int p = i; int q = 0; bool escape = false; while (p < n && q < m) { if (searchInto[p] == tosearch[q]) { if (tosearch[q] == '/' && !escape) { ++q; } else { ++p; ++q; } escape = false; } else if (!escape && tosearch[q] == '*') { ++q; while (q < m && p < n && searchInto[p] != tosearch[q]) ++p; escape = false; } else if (!escape && tosearch[q] == '?') { ++p; ++q; escape = false; } else if (tosearch[q] == '/' && !escape) { escape = true; ++q; } else break; } if (q == m) { return i; } if (q == m - 1 && tosearch[q] == '*') { if (q > 0 && tosearch[q - 1] == '/') continue; else return i; } } return ans; } int main() { string searchInto, tosearch; cout<< "Enter string:"; getline(cin, searchInto); cout << "Looking for :"; getline(cin, tosearch); if (tosearch.length() < 2) { char ch = tosearch.at(0); cout << "Found at: " <<charsearch(searchInto, ch) << endl; cout << "Used Char" << endl; } else cout << "Found at: " <<substr(searchInto, tosearch) << endl; return 0; }

var randomNumber = Math.floor(Math.random() * 50) + 1;
console.log(randomNumber);
var userGuess = document.querySelector("#guess");
document.getElementById("submit").addEventListener("click", submit, false);

function submit() {

  if (parseInt(userGuess) === randomNumber) {
    alert("You Win");
  } else {
    alert("You Lose");
  }
}

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

代码的问题是,您将完整的数据重新复制到适配器并再次将其设置为RecyclerView,这就是为什么它在RecyclerView中重新实例化,即滚动到顶部。除此之外,您可以尝试将更新的数据添加/附加到列表(您保存数据的位置),然后只需调用adapter.notifyDataSetChanged();方法。它会自动添加更新的数据,您无需再次设置回收站视图。

可能对于您的情况,您需要更改initDataView2() mehtod,如下所示

  private void initDataView2(ListPostModel listpost){
        GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
         mListPost.addAll(listpost.getListItemsPost());\
         mPostAdapter .notifyDataSetChanged();
    }

对于nextPageToken,你可以进入你的主代码onCreate()或你已经有适配器初始化的initDataView()方法

像这样,

  private void initDataView(ListPostModel listpost){
        GlobalFunction.saveString(this,GlobalVariable.keySharedPreference.TOKEN_PAGINATION, listpost.getNextPageToken());
        final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.keySharedPreference.TOKEN_PAGINATION);
        mListPost.addAll(listpost.getListItemsPost());
        mPostAdapter = new ListPostAdapter(mListPost, this) {
            @Override
            public void load() {
                ItemPostModel item = mListPost.get(mListPost.size()-1);
                if(nextPageToken==null){

                }else{
                    getNextListPost();
                }
            }
        };

        mRecyclerviewPost.setAdapter(mPostAdapter);
        //mPostAdapter.notifyDataSetChanged();

        mRecyclerviewPost.setHasFixedSize(true);
        mGridViewLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mGridViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        mRecyclerviewPost.setLayoutManager(mGridViewLayoutManager);
    }

我希望它能起作用:)。