【Android控制元件】呼吸效果的動畫
阿新 • • 發佈:2019-01-26
由於只是展示上的,就不需要使用屬性動畫。直接使用的補間動畫,簡單的動畫。
public class MainActivity extends Activity {
private ImageView mImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.testview); // 普通的imageview
mImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
hideRepeatBtn();
return false;
}
});
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showRepeatBtn();
}
});
showRepeatBtn();
}
/**
* 顯示呼吸效果動畫
*/
private void showRepeatBtn() {
mImageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// 觸控時取消動畫,並縮小,有按下的感覺
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
mImageView.setScaleX(0.9f);
mImageView.setScaleY(0.9f);
if (mImageView.getAnimation() != null) {
mImageView.getAnimation().cancel();
}
} else { // 鬆手後,恢復大小,並繼續呼吸效果
mImageView.setScaleX(1.0f);
mImageView.setScaleY(1.0f);
if (mImageView.getAnimation() != null) {
mImageView.getAnimation().start();
}
}
return false;
}
});
// 放大小時view,完全顯示後開始呼吸效果
ScaleAnimation enterAnim = new ScaleAnimation(0f, 1.1f, 0f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
enterAnim.setDuration(300); // 預設只執行一遍
enterAnim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
ScaleAnimation anim = new ScaleAnimation(1.0f, 1.1f, 1.0f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(750);
anim.setRepeatMode(Animation.REVERSE); // 放大並縮小,時間為750*2
anim.setRepeatCount(Animation.INFINITE); // 無限迴圈
mImageView.setAnimation(anim);
mImageView.startAnimation(mImageView.getAnimation());
}
});
mImageView.startAnimation(enterAnim);
}
/**
* 動畫隱藏連發按鈕
*/
private void hideRepeatBtn() {
// 縮小退出
ScaleAnimation anim = new ScaleAnimation(1.1f, 0f, 1.1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(300);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
if (mImageView.getAnimation() != null) {
mImageView.getAnimation().cancel();
}
}
});
mImageView.startAnimation(anim);
}
}