提问者:小点点

将数据添加到顶部而不会弄乱滚动?


我正在尝试添加一些日期在滚动顶部在一个回收器视图。这是工作,除了滚动,当一些新数据被添加时,它搞砸了一切。

我看到了这个主题:

链接1

链接2

但是他们都没有解决我的问题。

也许有人能帮我…

我使用volley获得一些数据,如下所示:

try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the object
                PostObj.setImageUrl(json.getString(Config.TAG_PPIC));
                ...


            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding object to the list
            listLf.add(0, PostObj); //0, postobj
        }

        //Notifying the adapter that data has been added or changed
        //adapter.notifyDataSetChanged(); the scroll will jump to position 0
        adapter.notifyItemRangeChanged(0, adapter.getItemCount()); // still not working
    }

我试图添加Adapter. NonofyItemRangeChanged(0,Adapter.getItemCount());但仍然是同样的事情。

我也试过:

// Save state
private Parcelable recyclerViewState;
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

// Restore state
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

它也不起作用。也许我把它放错了地方什么的…

我想要一些建议,我做错了什么,我如何获得新数据,通知适配器而不弄乱滚动位置?

编辑---------------------------------- 全班:

public class Comments extends BaseActivity {


    private List<LfGetSet> listLf;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    //Volley Request Queue
    private RequestQueue requestQueue;
    private String requestCount = "0";
    private String lastrequestCount = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ViewGroup content = (ViewGroup) findViewById(R.id.content_frame);
        getLayoutInflater().inflate(R.layout.activity_comments, content, true);

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerViewLf);
        recyclerView.setHasFixedSize(true);
        //layoutManager = new LinearLayoutManager(this);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);

        recyclerView.setLayoutManager(layoutManager);

        //Initializing our list
        listLf = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(this);

        //Calling method to get data to fetch data
        getData();

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) {
                    getData();
                }
            }
        });

        //initializing our adapter
        adapter = new LfAdapter(listLf, this);

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);


    }

    private JsonArrayRequest getDataFromServer(String requestCount) {
        ...
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    private void getData() {
        //Adding the method to the queue by calling the method getDataFromServer
        requestQueue.add(getDataFromServer(requestCount));
        lastrequestCount = requestCount;
        //Incrementing the request counter
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            //Creating the object
            LfGetSet PostObj = new LfGetSet();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the object
                PostObj.setImageUrl(json.getString(Config.TAG_PPIC));
                ...


            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding object to the list
            listLf.add(0, PostObj); //0, postobj
        }

        //Notifying the adapter that data has been added or changed
        adapter.notifyDataSetChanged();
    }

    //This method would check that the recyclerview scroll has reached the bottom or not
    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION
                    && lastVisibleItemPosition == 1
                    && lastrequestCount != requestCount
                    && requestCount != "0")
                return true;
        }
        return false;
    }

}

共1个答案

匿名用户

您可以尝试这种方法,按照常规将新项目添加到列表中,然后更新数组中的数据并将新数据放在顶部。

   // Add a new item the usual way so it goes at the bottom

    int x = 0;

   // Create a new Data list. New item goes 1st

   // Create a Loop

    myList.remove(x); // Remove item from the array at position

    MyList myList = new MyList();

    myList.add(x, theData); // Add data to array at position


    // Now that new data has been inserted to the Array at position X update the List item at that same Position. I usually do this in the Background.

    Handler handler = new Handler();

    final int finalX = x;
    final Runnable r = new Runnable() {
        public void run() {
            adapter.notifyItemChanged(finalX);  // Notify Adapter that the Items data has changed and Update
        }
    };

    handler.post(r);

    x++;

从DB读取更新的数据,然后用新数据动态更新列表项的代码。但在您的情况下,您需要添加1个新项目,并使用数组和列表中位置0的新项目数据更新列表。旧项目的位置移动了1。

public void updateStocks() {

        System.out.println("Updating");
        int rec = db.getRecordsCount() - 1;

        List<Records> record = db.getAllRecords();

        int x = 0;

        for (Records cn : record) {

            stocksList.remove(x);

            Livestocks stocks = new Livestocks();

            stocks.setID(cn.getID());
            stocks.setName(cn.getName());
            stocks.setTicker(cn.getTicker());
            stocks.setPrice(cn.getPrice());
            stocks.setOpen(cn.getOpen());
            stocks.setChange(cn.getChange());
            stocks.setPchange(cn.getPchange());
            stocks.setDhigh(cn.getDhigh());
            stocks.setDlow(cn.getDlow());
            stocks.setYhigh(cn.getYhigh());
            stocks.setYlow(cn.getYlow());
            stocks.setVol(cn.getVol());
            stocks.setShares(cn.getShares());
            stocks.setIown(cn.getIown());
            stocks.setMcap(cn.getMcap());
            stocks.setStatus(cn.getStatus());
            stocks.setExchange(cn.getExchange());

            stocksList.add(x, stocks);

            Handler handler = new Handler();

            final int finalX = x;
            final Runnable r = new Runnable() {
                public void run() {
                    adapter.notifyItemChanged(finalX);
                }
            };

            handler.post(r);

            x++;

            if (rec == x) {
            //do nothing
            }
        }

    }