Android
Animateurs
Recherche…
Secouer l'animation d'une ImageView
Sous le dossier res, créez un nouveau dossier appelé "anim" pour stocker vos ressources d'animation et mettez-le dans ce dossier.
shakeanimation.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fromDegrees="-15"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:toDegrees="15" />
Créer une activité vide appelée Landing
activity_landing.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imgBell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@mipmap/ic_notifications_white_48dp"/>
</RelativeLayout>
Et la méthode pour animer l'imageview sur Landing.java
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=this;
setContentView(R.layout.activity_landing);
AnimateBell();
}
public void AnimateBell() {
Animation shake = AnimationUtils.loadAnimation(mContext, R.anim.shakeanimation);
ImageView imgBell= (ImageView) findViewById(R.id.imgBell);
imgBell.setImageResource(R.mipmap.ic_notifications_active_white_48dp);
imgBell.setAnimation(shake);
}
Animation de fondu entrant / sortant
Pour afficher ou ObjectAnimator lentement, utilisez un ObjectAnimator . Comme indiqué dans le code ci-dessous, définissez une durée à l'aide de .setDuration(millis) où le paramètre millis correspond à la durée (en millisecondes) de l'animation. Dans le code ci-dessous, les vues s’afficheront ou disparaîtront plus de 500 millisecondes ou 1/2 seconde. Pour démarrer le ObjectAnimator animation d », appelez .start() . Une fois l'animation terminée, on onAnimationEnd(Animator animation) . Voici un bon endroit pour définir la visibilité de votre vue sur View.GONE ou View.VISIBLE .
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
void fadeOutAnimation(View viewToFadeOut) {
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(viewToFadeOut, "alpha", 1f, 0f);
fadeOut.setDuration(500);
fadeOut.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// We wanna set the view to GONE, after it's fade out. so it actually disappear from the layout & don't take up space.
viewToFadeOut.setVisibility(View.GONE);
}
});
fadeOut.start();
}
void fadeInAnimation(View viewToFadeIn) {
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(viewToFadeIn, "alpha", 0f, 1f);
fadeIn.setDuration(500);
fadeIn.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStar(Animator animation) {
// We wanna set the view to VISIBLE, but with alpha 0. So it appear invisible in the layout.
viewToFadeIn.setVisibility(View.VISIBLE);
viewToFadeIn.setAlpha(0);
}
});
fadeIn.start();
}
Animation TransitionDrawable
Cet exemple affiche une transaction pour une vue d'image avec seulement deux images (peut utiliser plus d'images l'une après l'autre pour les positions du premier et du deuxième calque après chaque transaction en boucle).
- Ajouter un tableau d'images à
res/values/arrays.xml
<resources>
<array
name="splash_images">
<item>@drawable/spash_imge_first</item>
<item>@drawable/spash_img_second</item>
</array>
</resources>
private Drawable[] backgroundsDrawableArrayForTransition;
private TransitionDrawable transitionDrawable;
private void backgroundAnimTransAction() {
// set res image array
Resources resources = getResources();
TypedArray icons = resources.obtainTypedArray(R.array.splash_images);
@SuppressWarnings("ResourceType")
Drawable drawable = icons.getDrawable(0); // ending image
@SuppressWarnings("ResourceType")
Drawable drawableTwo = icons.getDrawable(1); // starting image
backgroundsDrawableArrayForTransition = new Drawable[2];
backgroundsDrawableArrayForTransition[0] = drawable;
backgroundsDrawableArrayForTransition[1] = drawableTwo;
transitionDrawable = new TransitionDrawable(backgroundsDrawableArrayForTransition);
// your image view here - backgroundImageView
backgroundImageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(4000);
transitionDrawable.setCrossFadeEnabled(false); // call public methods
}
ValueAnimator
ValueAnimator introduit un moyen simple d’animer une valeur (d’un type particulier, par exemple int , float , etc.).
La manière habituelle de l'utiliser est:
- Créez un
ValueAnimatorqui animera une valeur deminàmax - Ajoutez un
UpdateListenerdans lequel vous utiliserez la valeur animée calculée (que vous pouvez obtenir avecgetAnimatedValue())
Vous pouvez créer le ValueAnimator deux manières:
(l'exemple de code anime un float de 20f à 40f en 250ms )
- De
xml(mettez le dans/res/animator/):
<animator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="250"
android:valueFrom="20"
android:valueTo="40"
android:valueType="floatType"/>
ValueAnimator animator = (ValueAnimator) AnimatorInflater.loadAnimator(context,
R.animator.example_animator);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator anim) {
// ... use the anim.getAnimatedValue()
}
});
// set all the other animation-related stuff you want (interpolator etc.)
animator.start();
- Du code:
ValueAnimator animator = ValueAnimator.ofFloat(20f, 40f);
animator.setDuration(250);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator anim) {
// use the anim.getAnimatedValue()
}
});
// set all the other animation-related stuff you want (interpolator etc.)
animator.start();
ObjectAnimator
ObjectAnimator est une sous-classe de ValueAnimator avec la possibilité d'ajouter la valeur calculée à la propriété d'une View target .
Tout comme dans ValueAnimator , il existe deux manières de créer ObjectAnimator :
(l'exemple de code anime un alpha d'un View de 0.4f à 0.2f dans 250ms )
- De
xml(mettez-le dans le/res/animator)
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="250"
android:propertyName="alpha"
android:valueFrom="0.4"
android:valueTo="0.2"
android:valueType="floatType"/>
ObjectAnimator animator = (ObjectAnimator) AnimatorInflater.loadAnimator(context,
R.animator.example_animator);
animator.setTarget(exampleView);
// set all the animation-related stuff you want (interpolator etc.)
animator.start();
- À partir du code:
ObjectAnimator animator = ObjectAnimator.ofFloat(exampleView, View.ALPHA, 0.4f, 0.2f);
animator.setDuration(250);
// set all the animation-related stuff you want (interpolator etc.)
animator.start();
ViewPropertyAnimator
ViewPropertyAnimator est un moyen simplifié et optimisé d'animer les propriétés d'une View .
Chaque View a un objet ViewPropertyAnimator disponible via la méthode animate() . Vous pouvez l'utiliser pour animer plusieurs propriétés à la fois avec un simple appel. Chaque méthode d'un ViewPropertyAnimator spécifie la valeur cible d'un paramètre spécifique que ViewPropertyAnimator doit animer.
View exampleView = ...;
exampleView.animate()
.alpha(0.6f)
.translationY(200)
.translationXBy(10)
.scaleX(1.5f)
.setDuration(250)
.setInterpolator(new FastOutLinearInInterpolator());
Remarque: L' appel de start() sur un objet ViewPropertyAnimator n'est PAS obligatoire. Si vous ne le faites pas, vous laissez simplement la plate-forme gérer le démarrage de l'animation au moment opportun (la prochaine manipulation de l'animation). Si vous le faites réellement (appelez start() ), assurez-vous que l'animation est lancée immédiatement.
Développer et réduire l'animation de la vue
public class ViewAnimationUtils {
public static void expand(final View v) {
v.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LayoutParams.WRAP_CONTENT
: (int)(targtetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int)(targtetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}