Reputation: 3059
I have an ImageView, initially empty. Its background is set to grey:
<ImageView
android:background="#333" />
After I fetch its bitmap from the internets, I want to set it as the src property, but fade it in gracefully. The animation examples I've seen for this do it like:
// fade_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<alpha
android:duration="2000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
but this is animating the opacity of the entire ImageView. It has the effect of first hiding the ImageView before fading it in, so you see a little pop at the start of the animation is the view as first set to alpha=0.
Is there a way to animate the opacity of just the "src" attribute instead of the entire ImageView?
Thanks
Upvotes: 4
Views: 1554
Reputation: 1082
Animations on imageView's source image is tricky and in most cases involve wraping imageView into some ViewGroup, but if all you want to do is animate its alpha (fade in/out), it is very easy to do using a TransitionDrawable:
TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{
new ColorDrawable(Color.TRANSPARENT),
getResources().getDrawable(R.drawable.my_image)
});
imageview.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(300);
Upvotes: 3
Reputation: 12929
You have 2 options:
1) Put a transparent ImageView
in a gray container (easy). The simplest container is FrameLayout
.
2) Animate the alpha of the contained image with the ImageView.setAlpha(int)
method. This method takes an integer as parameter, that ranges from 0 (fully transparent) to 255 (fully opaque). To animate a custom property like this, you'll need to use an ObjectAnimator
or NineOldAndroids.
Upvotes: 1
Reputation: 21082
Wrap the ImageView
inside a ViewGroup
such as LinearLayout
which will wrap_content
and will have all the settings you want to keep visible, such as the background color. Something like this:
<LinearLayout
android:layout_width='wrap_content'
android:layout_height='wrap_content'
android:background='#ff0000'>
<ImageView src='@drawable/ic_launcher'
android:layout_width='wrap_content'
android:layout_height='wrap_content'/>
</LinearLayout>
Which will result in the following results with an alpha
of 0.5 and 1 respectively.
Upvotes: 1