How to delay loading of RecyclerView items when it is present in ViewPager2 in android?

Viewed 570

I am using ViewPager2 to show data in fragments using RecyclerView inside respective fragment. There are 2 fragments. Each fragment contains 1 RecyclerView. Everything works fine, just one small problem, when I start activity which contains this ViewPager2, then if there are large number of items present then activity starts very slow. I know there are other solutions for this whole scenario for example reducing complex UI using ConstraintLayout, etc. But in my case I optimized all of that and still my activity startup time is slow.

So now I want to do the things in following way:

  1. Load activity -> Show loading... TextView -> Wait for some time before calling notifyDatasetChanged() of inner RecyclerView

So I am doing this using:

  final MaterialTextView loadingMTV = findViewById(R.id.loadingMTV);
    loadingMTV.postDelayed(new Runnable() {
        @Override
        public void run() {
            loadingMTV.setVisibility(View.GONE);
            recyclerViewAdapter.setTasks();
            completedRecyclerViewAdapter.setTasks();

            //setTasks() will contain notifyDatasetChanged() related logic
        }
    },500);

So it will delay inner content loading by 500 milliseconds. Now my activity startup time is as usual. Every thing works fine. Just one problem, I used 500 milliseconds as a delay time. I don't want this hardcoded value. So how to use proper delay time in this whole case?

1 Answers
  1. Creation of components inside the activity - the process of creating the activity itself, so until all internal Views are created, the Activity itself will not be created. Read more here

  2. Such problems are solved by transferring complex and lengthy computations to separate threads. You can use out-of-the-box asynchronous communication mechanisms such as RxJava. Thus, on another thread, you create View-components, and on the UI thread you only display them and interact with them.

Related