Search code examples
javaandroidfragmentandroid-scrollview

Scroll a ScrollView containing fragments to a specific fragment


I have a ScrollView where I create multiple Fragments under specific conditions. I want when I add a new fragment to the ScrollView to make it scroll so the Fragment is at the top most part of the screen. Here is my code :

From Fragment I call this inside onCreateView (As Fragments are generated dynamically)

((MainActivity)getActivity()).scrollToFrag(frag_number+"");

And inside my MainActivity.class

public final void scrollToFrag(final String frag){
    scrollView.postDelayed(new Runnable() {
        public void run() {
            scrollView.smoothScrollTo(0, getSupportFragmentManager().findFragmentByTag(frag).getView().getTop());
        }
    }, 100);
}

I notice a small scroll movement but not what I need ( The Fragment not reach the top at all)


Solution

  • Resolved the issue by running the code in a runnable inside the Fragment as well

    view.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((MainActivity)getActivity()).scrollToFrag(frag_number+"");
                    }
                }, 200);