Search code examples
androidmultithreadingandroid-recyclerviewandroid-handler

How to show recyclerview items in time interval?


I want to display recyclerview items after every 10 seconds. For instance, I have 8 items in my arraylist. Initially I want to display 3 items, then after waiting for 10 seconds first three visible items will disappear and next 3 items will show. how to achieve it ?

private void addList(){
        ItemAdapter itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.cachua);
        itemAdapter.setText("Tomato");
        mList.add(itemAdapter);

        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.bo);
        itemAdapter.setText("butter");
        mList.add(itemAdapter);

        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.cam);
        itemAdapter.setText("oranges");
        mList.add(itemAdapter);

        mAdapter = new ListAdapter(mList, this);
        mRecycleview.setAdapter(mAdapter);
        mRecycleview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter.notifyDataSetChanged();
        Log.d("anhtt","mlist : " +mList.size());
        mList.clear();


        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.quaxoai);
        itemAdapter.setText("mango");
        mList.add(itemAdapter);

        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.dau);
        itemAdapter.setText("strawberry");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mAdapter = new ListAdapter(mList, this);
        mRecycleview.setAdapter(mAdapter);
        mRecycleview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter.notifyDataSetChanged();
        Log.d("anhtt","mlist : " +mList.size());
        mList.add(itemAdapter);
        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.tao);
        itemAdapter.setText("Apple");
        mList.add(itemAdapter);

        mList.add(itemAdapter);
        itemAdapter = new ItemAdapter();
        itemAdapter.setImage(R.drawable.oi);
        itemAdapter.setText("guava fruit");
        mList.add(itemAdapter);
    }

Solution

  • Interesting scenario. I think instead of adding time delays in adapter you should do that stuff in your class where you are passing data to adapter. Try to load first 3 items which you want to show then use handler to make delay of 10 seconds.

    Like this :

     final Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            //Do your code to clear list and adding next 3 items and notify your adapter
          }
        }, 10000);
    

    After this you need to clear your list and add next 3 items in list and notify your adapter that data has been updated. With this approach you can achieve your use case.