Search code examples
androidandroid-layoutscrollviewandroid-viewandroid-scrollview

Scroll to bottom when dynamically inflating view


I have a LinearLayout and I'm inflating a CardView in it like this:

final LinearLayout itineraryDetailLL = (LinearLayout) findViewById(R.id.itineraryDetailLinearlayout);
final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);

The inflation of the child view is done on a onclick of a button. I want to scroll to the bottom of the screen whenever a new cardview is inflated. I'm doing it like this:

ScrollView scrollview = ((ScrollView) findViewById(R.id.masterScrollView));
scrollview.fullScroll(View.FOCUS_DOWN);

but this scrolls to somewhere middle of the screen and not to bottom. What am I doing wrong?


Solution

  • You have to post an event to happen on the next frame, when this ScrollView would be laid out:

    
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });