2016-10-31 53 views
0

的圖我使用以下代碼來擴大與動畫的視圖:動畫向左

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(); 
    } 

} 

上述代碼動畫從左至右當寬度變化的圖。

但是,我試圖從右到左對它進行動畫處理。換句話說,寬度應該朝相反的方向增長。我怎麼能做到這一點?

+0

不清楚你想要什麼,什麼是問題 –

回答

1

你在這裏處理的問題是一個錨定問題。視圖的錨(或樞軸點)確定視圖上的哪個點在其他部分更改時仍保持靜止。

視圖的錨點在調整其尺寸時很大程度上取決於視圖的佈局方式。由於您沒有提供任何有關如何在您發佈的代碼中展示您的視圖的信息,因此我會從您遇到的問題推斷出視圖的橫向錨點位於其左側。

這個錨定問題會產生一個增長,導致最左側保持不動,而右側擴展右側。

使視圖的左側向左擴展而右側保持靜止可以通過多種方式實現。一種方法是改變視圖在其父項中的佈局方式(即,如果父項是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(); 
    } 

正如你可以看到,這是一個位的「絕招」。在視圖向右擴展的同時,我們會以完全相同的比例將它向左移動,導致視圖向左擴展。

測試此代碼,看看它是否適合你。我還建議您看看您是否可以在視圖的容器內使用視圖的對齊或重力。這樣做會以更加標準的方式解決您的問題,即沒有任何「技巧」。

希望這會有所幫助。

+0

謝謝你的工作,但是觀點並不認爲是右向左擴展,而是右移。也可以移動視圖嗎? –

+0

也擴展視圖不完全可見 –