How to animate map padding in android

2019-06-21 13:01发布

问题:

I want to animate top map padding of a view programmatically but I have no idea how to do this.

private GoogleMap map;
map.setPadding(left, top, right, bottom);

Anyone have an idea how to animate top padding value from say 0 to 100 ?

回答1:

The map padding is not a view property nor a object property. You can test it by giving a padding to the map view:

<com.google.android.gms.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"/>

The result is that the map itself is padded which is different from

 map.setPadding(left, top, right, bottom);

setPadding is a method that offsets the UI controls inside the map. There is no property to animate. Luckily android offers the ValueAnimator. Your problem can be solved this way:

ValueAnimator animation = ValueAnimator.ofInt(0, paddingBottom);
animation.setDuration(150);
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {
        getMap().setPadding(0, 0, 0, Integer.parseInt(valueAnimator.getAnimatedValue().toString()));
    }
});
animation.start();

This basically animates an integer from 0 to paddingBottom without any context. You create the context in the onAnimationUpdate listener where you assign the animated padding value to the map padding.



回答2:

You would use Property Animation for that.



回答3:

final int newTopMargin = <value>;
Animation anim = new Animation() {

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        LayoutParams params = yourView.getLayoutParams();
        params.topMargin = (int)(newTopMargin * interpolatedTime);
        yourView.setLayoutParams(params);
    }
};

yourView.startAnimation(anim);

You can achieve the animation as described above, it won't be for padding though but it will set the margin with the animation effect you want.



回答4:

It's actually very simple to animate the padding changes without having to animate manually.

Right after setting the paddings, call

gooleMap.animateChanges(CameraUpdateFactory.newLatLngBounds(Bounds, padding));

or any of the CameraUpdateFactory helper methods.

It is easier and also much smoother than using a ValueAnimator, especially if you animate multiple padding sides.