Reputation: 16524
is there a way to apply a color to an alpha animation in android? I know how to use the <alpha>
element, but i'd like to have the alpha apply a color as well as an alpha so i can hightlight a layout. is this possible?
Upvotes: 4
Views: 5176
Reputation: 12627
Well, here is my solution animating a particular region of the screen (see demo down below). Please note that this code is targeting devices which run >= API9.
Beginner friendly, just copy and paste.
FadeAnimationColored.java
public class FadeAnimationColored {
private View view;
private float maxBrightness = 1.0f;
private float minBrightness = 0.0f;
private long duration = 400L;
private long startOffset = 0L;
private int color = android.R.color.white;
// Constructors...
public FadeAnimationColored(View view, String color, float maxBrightness, float minBrightness, long duration, long startOffset) {
this.view = view;
this.color = Color.parseColor(color);
this.maxBrightness = maxBrightness;
this.minBrightness = minBrightness;
this.duration = duration;
this.startOffset = startOffset;
prepareView();
}
public void fadeOut() {
this.view.setAlpha(1f);
Animation anim = new AlphaAnimation(minBrightness, maxBrightness);
anim.setDuration(duration);
anim.setStartOffset(startOffset);
anim.setFillEnabled(true);
anim.setFillAfter(true);
view.startAnimation(anim);
}
public void fadeIn() {
Animation anim = new AlphaAnimation(maxBrightness, minBrightness);
anim.setDuration(duration);
anim.setStartOffset(startOffset);
anim.setFillEnabled(true);
anim.setFillAfter(true);
view.startAnimation(anim);
}
private void prepareView() {
this.view.setBackgroundColor(this.color);
this.view.setAlpha(0f);
}
}
Next add an additional View to your layout, think of it as an overlay (I used a simple FrameLayout
which is set to match_parent
)
Here is a snippet which shows how to set up the animation in your Activity or Fragment:
FrameLayout interceptorFrame = (FrameLayout) mView.findViewById(R.id.fl_interceptor);
final FadeAnimationColored fadeAnimationLayout =
new FadeAnimationColored(interceptorFrame, MaterialColor.GREY_800, 0.9f, 0.0f, 400L, 0);
mFabMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
@Override
public void onMenuToggle(boolean opened) {
if (opened) {
fadeAnimationLayout.fadeOut();
} else {
fadeAnimationLayout.fadeIn();
}
}
});
Upvotes: 1
Reputation: 6643
Animations can not include color changes in Android--only alpha, rotation, scale, and translation are included.
That said, you can still make color changes by overlaying two objects of different colors on top of each other and fading the top one in or out.
You could also look into a TransitionDrawable or TextSwitcher to accomplish something similar. Hopefully we will be able to get full support for color animations in a future update.
Upvotes: 3