ViewPager setCurrentItem(pageId, true) does NOT smoothscroll

前端 未结 13 1152
予麋鹿
予麋鹿 2020-12-02 13:01

I am compiling on SDK 4.03, Samsung Infuse Android 2.2, Support Library for Android 4, and using ViewPager in my app, actual swipe works fine, but when I do



        
13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 13:41

    I'm aware this thread it pretty old, but this is one of the top Google results. I've been going back and forth on how to solve this problem for quite a bit now. None of the solutions above helped me at all. However, I did find a solution that works for me.

    What my setup currently looks like is a listview inside a viewpager. When you click on one of the views it creates a new page and scrolls to it. This was very snappy before, but it seems as though this is because I was calling

    mViewPager.setCurrentItem(intIndex, true);
    

    from inside my OnClickEvent. The viewpager doesn't like this for some reason, so instead, I made this function. It creates a new thread that runs a runnable on the UI thread. This runnable is what tells the ViewPager to scroll to a certain item.

    public static void scrollToIndex(int index) {
    
        final int intIndex = index;
    
        //We're going to make another thread to separate ourselves from whatever
        //thread we are in 
        Thread sepThread = new Thread(new Runnable(){
    
            public void run()
            {
                //Then, inside that thread, run a runnable on the ui thread.
                //MyActivity.getContext() is a static function that returns the 
                //context of the activity. It's useful in a pinch.
                ((Activity)MyActivity.getContext()).runOnUiThread(new Runnable(){
    
                    @Override
                    public void run() {
    
                        if (mSlidingTabLayout != null)
                        {
                            //I'm using a tabstrip with this as well, make sure
                            //the tabstrip is updated, or else it won't scroll
                            //correctly
                            if(mSlidingTabLayout.getTabStripChildCount() <= intIndex)
                            mSlidingTabLayout.updateTabStrip();
    
                            //Inside this thread is where you call setCurrentItem
                            mViewPager.setCurrentItem(intIndex, true);
    
                        }
    
                    }
    
                });
    
             }
        });
    
    
        sepThread.start();
    
    
    }
    

    I hope I have at least helped someone with this problem. Good luck!

    Edit: Looking over my answer, I'm pretty sure you can just run on the ui thread, and it should work. Take that with a grain of salt though, I haven't tested it yet.

提交回复
热议问题