Gradually fade out a custom, map marker

2020-08-05 11:27发布

问题:

I'm trying to gradually fade out a custom Google map marker.

I've seen all the posts that say to just use the drop in code from the DevBytes video and replace the setPosition with setAlpha, which is what I have attempted to do.

The problem is that whatever I do, my icon just goes white for the duration of the handler and then transparent upon completion, instead of gradually fading to complete transparency.

gMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(final com.google.android.gms.maps.model.Marker marker) {
        if (marker.equals(myLocationMarker)) {

            final long duration = 1000;
            final int alpha = 100;
            final long start = SystemClock.uptimeMillis();
            final Handler handler = new Handler();
            final Interpolator interpolator = new LinearInterpolator();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    long elapsed = SystemClock.uptimeMillis() - start;
                    float t = interpolator.getInterpolation((float) elapsed / duration);

                    float newAlpha = alpha - (t*100);
                    if(newAlpha<0)
                        newAlpha = 0;
                    int finalAlpha = (int)Math.ceil(newAlpha);
                    System.out.println("time = "+t);
                    System.out.println("newAlpha = "+newAlpha);
                    System.out.println("finalAlpha = "+finalAlpha);
                    marker.setAlpha(finalAlpha);

                    if (t < 1.0)
                        handler.postDelayed(this, 10);
                }
            });
            return true;
        }
    });

回答1:

I tried using ValueAnimator and it worked:

ValueAnimator ani = ValueAnimator.ofFloat(1, 0); //change for (0,1) if you want a fade in
ani.setDuration(5000);
ani.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        marker.setAlpha((float) animation.getAnimatedValue());
    }
});
ani.start();