Android animation only when ListView scrolls down

2020-08-02 04:04发布

问题:

I have a ListView in a layout, I need to apply animation (appearing from bottom to top) only when list is scrolled down.

How can I do it?

Please help me.

回答1:

Hope this will help you out. Google plus animation

up_from_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:anim/decelerate_interpolator">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="100%" android:toYDelta="0%"
        android:duration="400" />
</set>

down_from_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:anim/decelerate_interpolator">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="-100%" android:toYDelta="0%"
        android:duration="400" />
</set>

Code:

private int lastPosition = -1;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //Load your view, populate it, etc...
    View view = ...;

    Animation animation = AnimationUtils.loadAnimation(getContext(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
    view.startAnimation(animation);
    lastPosition = position;

    return view;
}


回答2:

add animation to specific view (could be ImageView , LinearLayout ...) , animation will start when getView method called mean when adapter inflate any new item

 @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        setAnimation(YOUR_VIEW, position);
    }

 private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition) // you can put any rule you need 
        {
            Animation animation = AnimationUtils.loadAnimation(_Context, R.anim.push_left_in); // add any animation you want 
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }