属性动画是我们开发过程中经常使用的一种动画,不仅使用方便,而且改变view的属性.不过如果使用不当就会造成动画失效
一位兄弟跟我说他在自定义的view中使用了属性动画ValueAnimator,可是动画突然不起作用,而之前在Activity中使用一直都是好好的,让我帮忙看一下,查看他的代码发现他的view是这么定义的(核心部分代码)
public UiXKMenuView(Context context) {
this(context, null);
}
public UiXKMenuView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public UiXKMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
initView();
}
private void initView() {
View view = LayoutInflater.from(mContext).inflate(R.layout.view_xkemenu, null);
addView(view);
...
}
他的xml文件R.layout.view_xkemenu是这么写的
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/ui_xkbackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#99000000"
/>
android:id="@+id/menu_content_layout"
android:layout_width="wrap_content"
android:layout_height="325dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="72px"
android:layout_marginBottom="-325dp"
android:gravity="right"
android:orientation="vertical"
>
android:layout_width="wrap_content"
android:layout_height="48dp">
android:id="@+id/menu_pic"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:layout_alignParentRight="true"
android:src="@drawable/mm1"
/>
android:id="@+id/image_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_marginRight="30px"
android:layout_toLeftOf="@+id/menu_pic"
android:gravity="center"
android:text="妹纸"
android:textColor="#fff"
android:textSize="39px"
/>
...
使用动画的过程是
public void showView() {
final int height = dp2px(425f);
if (animator != null) animator.cancel();
animator = new ValueAnimator();
animator.setDuration(500);
animator.setFloatValues(1f, 0f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) menuLayout.getLayoutParams(); //menuLayout对应xml中id="@+id/menu_content_layout"的LinearLayout
lp.bottomMargin = new Float((-1 * ((Float) animator.getAnimatedValue()) * height)).intValue();
menu_content_layout.setLayoutParams(lp);
if(UiXKMenuView.this.getVisibility() == View.GONE)
UiXKMenuView.this.setVisibility(VISIBLE);
}
});
animator.start();
}
使用的效果是:
失效动画.gif
代码很常规, 乍一看也没毛病, 但机智如你一定看出了一些端倪,于是我给他的xml做了一点修改:
xmlns:android&#