簡體   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