繁体   English   中英

向左动画视图

[英]Animate a view towards left

我正在使用以下代码来扩展带有动画的视图:

public class HorizontallyAnimate extends Animation {

    private int  toWidth;
    private int  startWidth;
    private View view;
    private String TAG = HorizontallyAnimate.class.getSimpleName();
    private int newWidth;
    public HorizontallyAnimate(View view) {
        this.view = view;
        this.startWidth = this.view.getWidth();
        this.toWidth = (this.startWidth == view.getHeight() ? this.startWidth * 4 : view.getHeight());

        Log.d(TAG,"Start width" + this.startWidth);
        Log.d(TAG,"view hieght " + view.getHeight());

    }

    protected void applyTransformation(float interpolatedTime, Transformation t) {
        newWidth = this.startWidth + (int) ((this.toWidth - this.startWidth) * interpolatedTime);
        this.view.getLayoutParams().width = newWidth;
        this.view.requestLayout();
    }

}

上面的代码在宽度改变时从左到右动画化视图。

但是,我正在尝试从右到左对其进行动画处理。 换句话说,宽度应沿相反的方向增长。 我该怎么做?

您在这里处理的问题是一个锚定问题。 视图的锚点(或枢轴点)确定其他部分发生更改时视图上的哪个点保持静止。

调整视图尺寸时,其锚点高度取决于视图的布局方式。 由于您没有在发布的代码中提供有关视图布局的任何信息,因此从您遇到的问题来看,我认为该视图的水平锚点位于其左侧。

此锚定问题将产生增长,这将导致最左侧保持静止,而右侧向右扩展。

可以通过几种方法使视图的左侧向左扩展而右侧保持不动。 一种方法是更改​​视图在其父级中的布局方式(即,如果父级是RelativeLayout ,则将视图设置为alignParentRight=true ,或者在其他容器中使用gravity进行播放)。

但是,由于您没有指定视图的布局方式,因此我将为您提供一个不对其容器进行任何假设的解决方案。 该解决方案并不完美,因为它可能会引起一些卡顿现象,但是它仍然可以实现您要执行的操作。

在您的applyTransformation方法中,您需要通过向左平移来补偿正确的增长。 您可以使用translationX对此进行补偿:

protected void applyTransformation(float interpolatedTime, Transformation t) {

        // hold the change in a separate variable for reuse.
        int delta = (int) ((this.toWidth - this.startWidth) * interpolatedTime);

        newWidth = this.startWidth + delta;
        this.view.getLayoutParams().width = newWidth;

        // shift the view leftwards so that the right side appears not to move.
        // shift amount should be equal to the amount the view expanded, but in the
        // opposite direction.
        this.view.setTranslationX(-delta); 

        this.view.requestLayout();
    }

如您所见,这有点“技巧”。 当视图向右扩展时,我们以完全相同的比例将其向左移动,这导致视图向左扩展的错觉。

测试此代码,看看它是否对您有用。 我还建议您查看是否可以从其容器中浏览视图的对齐方式或重力。 这样做将以更标准的方式解决您的问题,即没有任何“技巧”。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM