Use smoothScrollTo in Fragment

android, android-fragments, android-scroll, navigation-drawer

Solution

Try calling `smoothScrollTo` method in calling `post` of the view:

ScrollView scrollView = (ScrollView)getView().findViewById(scrollID);
scrollView.post(new Runnable() {

    @Override
    public void run() {
        scrollView.smoothScrollTo(0,(getView().findViewById(relativeID)).getTop());
    }
});

Problem

I have following situation: I'm using a Navigation Drawer to make the user easily navigate between different topics. You can find a picture here: https://drive.google.com/file/d/0B2gMUEFwlGRfSHRzVlptYmFQTXc/edit?usp=sharing When clicking on a heading, like General the only the main content view is replaced, by using a fragment and a layout file. But when the user clicks on a subheading, like Gameplay, the layout changes, AND it should scroll down to a specifc view in the layout. So in my fragment class I'm using the "onViewCreated" method and the smoothScrollTo method, provided by a ScrollView. The ScrollView and the RelativeLayout are both not null, and set to the right id, set in "onCreateView" Codesnippets: ``` @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (getArguments().getBoolean(ARG_BOOL)) { scrollView = (ScrollView)getView().findViewById(scrollID); relativeLayout = (RelativeLayout)getView().findViewById(relativeID); ((ScrollView)getView().findViewById(scrollID)).smoothScrollTo( 0, (getView().findViewById(relativeID)).getLeft()); Toast.makeText(getApplicationContext(), "SCROLL",Toast.LENGTH_SHORT). show(); } } ``` The problem is that it is not executing the "smoothScrollTo" method, while the toast gets executed. Here I call the fragment (boolean scroll is used to control the smoothScrollTo method): ``` private void selectItem(int Id, boolean scroll) { Fragment fragment = new ContentFragment(); Bundle args = new Bundle(); args.putBoolean(ContentFragment.ARG_BOOL, scroll); args.putInt(ContentFragment.ARG_ITEM_ID, Id); fragment.setArguments(args); // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); // Highlight the selected item, update the title, and close the drawer TextView textView = (TextView) findViewById(Id); getActionBar().setTitle(textView.getText()); mDrawerLayout.closeDrawer(mDrawerList); } ``` Thanks for your help ;-) EDIT: SOLUTION: ``` if (getArguments().getBoolean(ARG_BOOL)) { getView().findViewById(scrollID).post(new Runnable() { @Override public void run() { ((ScrollView) getView().findViewById(scrollID)). smoothScrollTo(0, (getView().findViewById(relativeID)).getTop()); } }); } ```

Original source