3

I've seen some similar posts here but no appropriate answer.

I use the event onpageselected in a viewpager to execute a function. This function is network dependent so it can take some time. But then the slide animation looks laggy.

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {
                makeSomeHeavyTask();
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

Heavy Task:

public void makeSomeHeavyTask() {
        handler.post(new QueryRunnable());

    }

Is there a way to solve this? Thanks

user2212461
  • 3,105
  • 8
  • 49
  • 87

2 Answers2

1

Do the heavy task with an AsyncTask. Check out the accepted answer here AsyncTask: where does the return value of doInBackground() go?

EDIT: You need to return a placeholder in the getView first. If the getView method has to wait for the thread to finish, then the animation will lag for sure. The returned placeholder can later be used to do posting after thread has finished.

Community
  • 1
  • 1
Shakti
  • 1,581
  • 2
  • 20
  • 33
  • I do it already in another thread through my Handler. ( see in the function makesomeheavytask(). Is there a way to do the slide animation in a async task?! – user2212461 Jan 25 '14 at 11:37
  • Animation can only be done in the UI/main thread. Everything else you can offload to threads. – Shakti Jan 25 '14 at 15:48
  • Well that only works if your heavy task has does not maniupulate UI, if you want to change Views when page changes you out of luck. – Patrick Aug 19 '15 at 13:33
0

You could use the callback

public void onPageScrollStateChanged(int i)

instead of public void onPageSelected(int i) with

if(i == ViewPager.SCROLL_STATE_IDLE) {
    //your task
}

if you have a task that cannot be executed on a different thread. This will be called after the animation is finished.

Patrick
  • 33,984
  • 10
  • 106
  • 126