1
votes

I would like to scroll a screen to a particular position when the screen is displayed so i did this code in Onresume function of my fragment

  scrollView.post(new Runnable() {
        @Override public void run () {
            scrollView.scrollTo(0, -200);
            Log.d(TAG, "x: " + scrollView.getScrollX() + " " + "y: " + scrollView.getScrollY());
        }
    }

    );

but the scrollview doesn 't scroll

1

1 Answers

3
votes

I've encountered the same problem with scrolling fragment to the previous position when returning to it. No scrolling possible in onResume(). I suspect when you post runnable (as you mention in your question) there is no guarantee whether it will work.

I've found 2 solutions, hope this helps:

1) More general approach, still it doesn't work for API level < 11:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // inflate your main view
    mView = inflater.inflate(R.layout.your_fragment_id, container, false);

    // find your scroll view
    mScrollContainer = (ScrollView) mView.findViewById(R.id.scroll_container);


    // add OnLayoutChangeListener
    mView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

                // get your X and Y to scroll to 
                ...
                mScrollContainer.scrollTo(x,y);
            }
        }
    });
}

You should get X and Y from your own source (say your own bundle), since in most cases - when activity doesn't save it's state - you just can't use fragment's savedInstanceState (see here)

2) More specific but sometimes more useful method is to set OnFocusChangeListener for the element that gets focus after fragment is shown:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...

    mListView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
        // do your scrolling here   
        }
    });
}