如何剪切Transition Animation仅在子视图中绘制?

时间:2012-10-04 07:00:18

标签: android android-animation

我正在为活动中的视图运行过渡动画,从屏幕顶部到底部。这是屏幕标题视图的顶部。如何仅在视图中(仅对于孩子)或从特定的Y或X位置应用动画?

我正在使用以下代码

XML代码

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
<translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="500" />
</set>

Java代码

Animation in = AnimationUtils.loadAnimation(_activity, R.anim.in_from_top);
view.setAnimation(in);

现在这个视图来自屏幕顶部。我希望动画在特定的X,Y点而不是屏幕的顶部开始。根据我的要求,动画视图将出现在活动标题之上,这是一个缺陷。

2 个答案:

答案 0 :(得分:1)

如果您已将两个孩子添加到单个家长,则会出现此问题。将子项添加到另一个布局,然后将此布局添加到实际布局。这将解决您的问题。

答案 1 :(得分:0)

您需要创建一个类似这样的自定义动画类:

public class ExpandAnimation extends Animation {
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;

/**
 * Initialize the animation
 * 
 * @param view
 *            The layout we want to animate
 * 
 * @param duration
 *            The duration of the animation, in ms
 */
public ExpandAnimation(View view, int duration) {
    setDuration(duration);
    mAnimatedView = view;
    mViewLayoutParams = (LayoutParams) view.getLayoutParams();
    mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
    mMarginStart = mViewLayoutParams.bottomMargin;
    mMarginEnd = (mMarginStart == 0 ? (0 - view.getHeight()) : 0);
    view.setVisibility(View.VISIBLE);
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    super.applyTransformation(interpolatedTime, t);

    if (interpolatedTime < 0.5f) {
        mViewLayoutParams.bottomMargin = mMarginStart + (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
        mAnimatedView.requestLayout();
    } else if (!mWasEndedAlready) {
        mViewLayoutParams.bottomMargin = mMarginEnd;
        mAnimatedView.requestLayout();

        if (mIsVisibleAfter) {
            mAnimatedView.setVisibility(View.GONE);
        }
        mWasEndedAlready = true;
    }
}

}

然后将此动画应用于您想要的x,y坐标。

假设您在某个x,y坐标处有一个按钮,并且在其单击时我们为视图设置动画,然后将其向后滚动。你必须做这样的事情:

 private View previous = null;
 private void doTransformation() {
    if (previous != null) {
        ((LinearLayout.LayoutParams) previous.getLayoutParams()).bottomMargin = -200;
        ExpandAnimation anim = new ExpandAnimation(previous, 300);
        previous.startAnimation(anim);
        previous = null;
    } else {
        View yourlayout= findViewById(R.id.your_layout);
        ExpandAnimation anim = new ExpandAnimation(yourLayout, 300);
        detailLayout.startAnimation(anim);
        previous = yourLayout;
    }
}