RecyclerView分页不保持滚动位置

时间:2017-11-07 15:06:14

标签: android

我是android的新手,我一直在使用recyclercview进行分页。我从服务器(运行php)接收我的数据并以JSON格式返回它,它将数据以1-10,11-20等串起来。我用这个调用notifyDataSetChanged。但问题是,在检索更多数据而不是保留当前位置时,recyclerview会回滚到顶部。我该怎么做?

当滚动条到达底部时,它会触发asynctask

AsynTask:

    public class LoadRecharge extends AsyncTask<String, String, String> {

    private boolean socketTimeout = false;
    Context context;
    public static final String TAG = "custom_message";
    public AsyncResponse delegate = null;
    private String server_url = "https://blockgator.com/mobile/endless.php";

    public LoadRecharge(Context ctxt, AsyncResponse asyncResponse) {
        delegate = asyncResponse;
        context = ctxt;
    }

    @Override
    protected String doInBackground(String... params) {
        if (connectGoogle()) {

            String post_data = "";

            try {
                URL url = new URL(server_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                post_data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

                return result;
            } catch (IOException e) {
                Log.e(TAG, "error: " + e.getMessage());
            }
        } else {
            this.socketTimeout = true;
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        arr.add(null);
        scrollAdapter.notifyItemInserted(arr.size() - 1);
    }

    @Override
    protected void onPostExecute(String result) {
        arr.remove(arr.size() - 1);
        scrollAdapter.notifyItemRemoved(arr.size());

        if (this.socketTimeout) {
            Toast.makeText(context, "unable to connect to server", Toast.LENGTH_SHORT).show();
        } else {
            delegate.processFinish(result);
        }
    }

    public boolean connectGoogle() {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setConnectTimeout(3000);
            urlc.connect();
            return (urlc.getResponseCode() == 200);

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

@Override
public void processFinish(String output) {
    try {
        JSONObject jsonObject = new JSONObject(output);
        if (jsonObject.get("status").toString().equals("success")) {
            JSONArray jsonarr = jsonObject.getJSONArray("data");
            String columns[] = {"id", "bill_amount", "bill_price", "variation"};
            for (int i = 0; i < jsonarr.length(); i++) {
                ArrayList<String> temp = new ArrayList<>();
                for (String column : columns) {
                    temp.add(jsonarr.getJSONObject(i).getString(column));
                }
                arr.add(temp);

                setAdapter(arr);
            }
        } else if (jsonObject.get("status").toString().equals("end")) {
            total = "end";
        }


    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(this, "exception from json", Toast.LENGTH_LONG).show();
    } catch (NullPointerException e) {
        Toast.makeText(this, "Unable to connect to server...", Toast.LENGTH_LONG).show();
        Toast.makeText(this, "Null from json", Toast.LENGTH_LONG).show();
    }
}

public void setAdapter(ArrayList<ArrayList<String>> arr) {
    recycler.setAdapter(scrollAdapter);
    scrollAdapter.notifyDataSetChanged();
    scrollAdapter.setLoading();
    scrollAdapter.setOnItemClickListener(this);
    scrollAdapter.setOnLoadMoreListener(this);
}

2 个答案:

答案 0 :(得分:2)

删除此行recycler.setAdapter(scrollAdapter);您只需在Activity的onCreate方法或Fragment的onCreateView方法中设置适配器一次。

答案 1 :(得分:0)

在setAdapter()中,您不需要再次执行 recycler.setAdapter(scrollAdapter); ,只需在开头执行

我做了类似的事情,但是反过来,正在聊天

messages.addAll(0, oldMessages);

mAdapter.notifyItemRangeInserted(0, oldMessages.size());
mAdapter.notifyItemChanged(oldMessages.size());
mAdapter.setLoaded();

我将char的旧消息添加到消息中。

然后通知适配器我更新了源

我使用0来开头