Android 佈局平鋪展開效果的屬性動畫
package com.udream.stylist.app.utils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
/**
* Created by debbytang.
* Description:顯示隱藏佈局的屬性動畫(鋪展)
* Date:2017/3/30.
*/
public class HiddenAnimUtils {
private int mHeight;//伸展高度
private View hideView,down;//需要展開隱藏的佈局,開關控制元件
private RotateAnimation animation;//旋轉動畫
/**
* 構造器(可根據自己需要修改傳參)
*
* @param hideView 需要隱藏或顯示的佈局view
* @param down 按鈕開關的view
* @param height 佈局展開的高度(根據實際需要傳)
*/
public static HiddenAnimUtils newInstance(Context context,View hideView,View down,int height){
return new HiddenAnimUtils(context,hideView,down,height);
}
private HiddenAnimUtils(Context context,View hideView,View down,int height){
this.hideView = hideView;
this.down = down;
float mDensity = context.getResources().getDisplayMetrics().density;
mHeight = (int) (mDensity * height + 0.5);//伸展高度
}
/**
* 開關
*/
public void toggle(){
startAnimation();
if (View.VISIBLE == hideView.getVisibility()) {
closeAnimate(hideView);//佈局隱藏
} else {
openAnim(hideView);//佈局鋪開
}
}
/**
* 開關旋轉動畫
*/
private void startAnimation() {
if (View.VISIBLE == hideView.getVisibility()) {
animation = new RotateAnimation(180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
} else {
animation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
}
animation.setDuration(30);//設定動畫持續時間
animation.setInterpolator(new LinearInterpolator());
animation.setRepeatMode(Animation.REVERSE);//設定反方向執行
animation.setFillAfter(true);//動畫執行完後是否停留在執行完的狀態
down.startAnimation(animation);
}
private void openAnim(View v) {
v.setVisibility(View.VISIBLE);
ValueAnimator animator = createDropAnimator(v, 0, mHeight);
animator.start();
}
private void closeAnimate(final View view) {
int origHeight = view.getHeight();
ValueAnimator animator = createDropAnimator(view, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
}
});
animator.start();
}
private ValueAnimator createDropAnimator(final View v, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator arg0) {
int value = (int) arg0.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
layoutParams.height = value;
v.setLayoutParams(layoutParams);
}
});
return animator;
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
...
case R.id.down:
HiddenAnimUtils.newInstance(xxx.this,xxx,down,77).toggle();
breake;
...