1. 程式人生 > 程式設計 >android 實現控制元件左右或上下抖動教程

android 實現控制元件左右或上下抖動教程

差不多一年前在自己的專案中用過這效果,雖然很簡單,但還是寫寫。

1、首先在你的res目錄下新建anim子目錄,並在anim目錄下新建兩個檔案:

(1)shake.xml檔案(位移/平移:translate),設定起始的位移範圍、效果時間、迴圈次數

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromXDelta="0"
  android:toXDelta="10"
  android:duration="500"
  android:interpolator="@anim/share_cycle">
  <!--.
    fromXDelta:x軸起點抖動位置
    toXDelta:x軸終點抖動位置
    duration:迴圈播放的時間
    interpolator:迴圈不放設定(次數)
  -->
</translate>

(2)cycle.xml檔案,控制迴圈次數

<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
  android:cycles="2"><!--. 迴圈次數 -->

</cycleInterpolator><!--. 迴圈播放 -->

最後給你的控制元件設定改動畫屬性

Animation shake = AnimationUtils.loadAnimation(this,R.anim.shake);

ivShake.startAnimation(shake);

這裡ivShake是ImageView,就是這麼簡單。

2、個人碰到一個問題就是在Activity實現監聽中新增動畫效果第一次沒有反應,不知道為什麼

補充知識:Android 抖動提示動畫

左右抖動

ObjectAnimator animator = ObjectAnimator.ofFloat(textView,"translationX",100,-100,0);
animator.setDuration(200);
animator.start();

重複左右抖動

Animation translateAnimation = new TranslateAnimation(-20,20,0);
translateAnimation.setDuration(100);//每次時間
translateAnimation.setRepeatCount(10);//重複次數
/**倒序重複REVERSE 正序重複RESTART**/
translateAnimation.setRepeatMode(Animation.REVERSE);
nope.startAnimation(translateAnimation);
  public static void Shakeview( View view) {
    Animation translateAnimation = new TranslateAnimation(-10,10,0);
    translateAnimation.setDuration(50);//每次時間
    translateAnimation.setRepeatCount(10);//重複次數
/**倒序重複REVERSE 正序重複RESTART**/
    translateAnimation.setRepeatMode(Animation.REVERSE);
    view.startAnimation(translateAnimation);
  }

左右上下抖動

ObjectAnimator animator = tada(clickMe);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.start();
 

public static ObjectAnimator tada(View view) {
  return tada(view,2f);
}
 
public static ObjectAnimator tada(View view,float shakeFactor) {
 
  PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofKeyframe(View.SCALE_X,Keyframe.ofFloat(0f,1f),Keyframe.ofFloat(.1f,.9f),Keyframe.ofFloat(.2f,Keyframe.ofFloat(.3f,1.1f),Keyframe.ofFloat(.4f,Keyframe.ofFloat(.5f,Keyframe.ofFloat(.6f,Keyframe.ofFloat(.7f,Keyframe.ofFloat(.8f,Keyframe.ofFloat(.9f,Keyframe.ofFloat(1f,1f)
  );
 
  PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofKeyframe(View.SCALE_Y,1f)
  );
 
  PropertyValuesHolder pvhRotate = PropertyValuesHolder.ofKeyframe(View.ROTATION,0f),-3f * shakeFactor),3f * shakeFactor),0)
  );
 
  return ObjectAnimator.ofPropertyValuesHolder(view,pvhScaleX,pvhScaleY,pvhRotate).
      setDuration(1000);
}

以上這篇android 實現控制元件左右或上下抖動教程就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。