在分页时,RecyclerView会跳到顶部

时间:2015-03-30 19:25:40

标签: java android pagination android-recyclerview

尝试在RecyclerView中实现分页,但当RecyclerView到达终点并且应用程序开始加载新部分数据时,RecyclerView会跳转到它的顶部。

cityListRecyclerview = (RecyclerView) findViewById(R.id.recyclerView);
    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    cityListRecyclerview.setLayoutManager(linearLayoutManager);
    loadFromUrl();

    cityListRecyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            visibleItemCount = linearLayoutManager.getChildCount();
            totalItemCount = linearLayoutManager.getItemCount();
            pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
                    loading = false;
                    page++;
                    url += Api.OFFSET_URL + String.valueOf(page);
                    loadFromUrl();
                    Log.v("LIST", "Last Item Wow !");
                }
            }
        }
    });

loadFromUrl()方法:

public void loadFromUrl() {

    Ion.with(MainActivity.this)
            .load(url)
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {

                @Override
                public void onCompleted(Exception e, JsonObject jsonObject) {
                    progressDialog.dismiss();

                    JsonArray jsonArray = jsonObject.getAsJsonArray("flats");

                    jsonObjectToPass = jsonArray;

                    for(int i = 0; i < jsonArray.size(); i++) {
                        JsonElement obj = jsonArray.get(i);
                        JsonObject jsonObject1 = obj.getAsJsonObject();
                       ............ here parsing JSON object and nothing interesting
                        adapter = new OffersAdapter(MainActivity.this, cityList);
                        adapter.setClickListener(MainActivity.this);
                        loading = true;
                        cityListRecyclerview.setAdapter(adapter);
                    }

                }

            });

}

XML文件:

    <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

gradle文件:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'}

所以有人能说出我做错了什么吗?

1 个答案:

答案 0 :(得分:4)

所以问题真的很愚蠢!首先,我将这两件事转移到onCreate()

adapter = new OffersAdapter(MainActivity.this, cityList);
cityListRecyclerview.setAdapter(adapter);

并添加了

adapter.notifyDataSetChanged();

在loadFromUrl()方法中,现在一切正常:D也许如果有人会遇到同样的问题,那么他会看到我的帖子:D