Android: scroll down after animation of LinearLayout.addview

3.3k views Asked by At

I want to make a list of items which are in a Scrollview. So I put a LinearLayout inside a Scrollview. There is already one item inside the linearLayout: a view to add items. I want that item to stay at the bottom of my list at all times. (which a accomplished)

But when I add an item by executing the code below, my item to add views goes out of the screen.

linearLayout.addView(theview, linearLayout.getChildCount() - 1);

The views get inserted animated:

screen.android:animateLayoutChanges="true"

So my Question is how I scroll my scrollView down during the animation, so my item stays on the screen.

These are some screenshots.
my screenshots

Thanx

2

There are 2 answers

0
Alex_297 On

Realization for a smooth scroll for ScrollView after layout animation ends.

First add LayoutTransition type in the code, not in xml

final LayoutTransition layoutTransition = mainLinearLayoutContainer.getLayoutTransition();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
    layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
}
layoutTransition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);

Then create LayoutTransition.TransitionListener item to have ability to multiple adding/removing it. Also you need to remove transitionListener in the end of translation because endTransition() callback is called multiple times and it brokes smoothScroll.

final LayoutTransition.TransitionListener transitionListener = new LayoutTransition.TransitionListener() 
{
    @Override
    public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {}

    @Override
    public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) 
    {
        // Remove TransitionListener because endTransition is called multiple times and it brokes smoothScroll
        layoutTransition.removeTransitionListener(this);
        scrollContainer.post(new Runnable() 
        {
            @Override
            public void run() {
                scrollContainer.smoothScrollTo(0, scrollContainer.getBottom());
            }
        });
    }
};

Finnaly add animation start point.

button.setOnClickListener(new View.OnClickListener() 
{
    @Override
    public void onClick(View v) 
    {
        if (licenseLabel.getVisibility() == View.GONE) 
        {
            layoutTransition.addTransitionListener(transitionListener);
            button.setVisibility(View.VISIBLE);
        } 
        else {
            licenseLabel.setVisibility(View.GONE);
        }
    }
});
0
Tico Fortes On

You should call scrollTo or fullScroll inside post method, after addView.

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

ref: How to Programmatically Scroll a ScrollView to Bottom