2014-01-08 62 views
2

我想將視圖(以我的例子 - 一個按鈕,但實際上並不重要)移動到屏幕的中心。 當我運行沒有動畫的移動時,它可以工作。然而,我很難決定我應該使用哪些動畫來做,因爲TranslateAnimation只允許我這樣做,但指定了我沒有的確切的x,y座標(用度量值試過,但是計算不起作用,我不想使用這種方法)。如何在Android中使用動畫將視圖移動到屏幕中心

因此,此代碼的工作,而不動畫:

RelativeLayout.LayoutParams parms2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
parms2.addRule(RelativeLayout.CENTER_VERTICAL); 
parms2.addRule(RelativeLayout.CENTER_HORIZONTAL); 
_buttonC.setLayoutParams(parms2); 

,當我嘗試添加動畫,事實並非如此。

ObjectAnimator ani = ObjectAnimator.ofFloat(_buttonC, "Y", 2000); 
ani.setDuration(4000); 
ani.addListener(new AnimatorListenerAdapter() 
{ 
    @Override 
    public void onAnimationStart(Animator animation) { 

     RelativeLayout.LayoutParams parms2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
     parms2.addRule(RelativeLayout.CENTER_VERTICAL); 
     parms2.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     _buttonC.setLayoutParams(parms2);    
    } 


    @Override 
    public void onAnimationEnd(Animator animation) 
    { 

    } 
}); 

任何幫助,將不勝感激:)

回答

11

你試過:

_buttonC.animate().translationX(parentCenterX - _buttonC.getWidth()/2).translationY(parentCenterY - _buttonC.getHeight()/2); 

當然,你將不得不計算父中心X和centerY:

float parentCenterX = parent.getX() + parent.getWidth()/2; 
float parentCenterY = parent.getY() + parent.getHeight()/2; 

希望這會有所幫助。

+0

它應該是' translationX(parentCenterX - _buttonC.getWidth()/ 2 - _buttonC.getX())' – user3995789

+0

您救了我.. –

0

我不知道這是不是問題,但請嘗試:

ObjectAnimator ani = ObjectAnimator.ofFloat(_buttonC, "translationY", 2000); 
... 
ani.start(); 
+0

onAnimationStart EXISTS .... – dusm

+0

您不必使用ani.start() - 只是用代替將Y – Frame91

+0

translationY是的,我試過了已經,沒有工作:( – dusm

0

private void moveSearchViewDown(){ 查看edit_text = findViewById(R.id.edit_text);

DisplayMetrics metrics = this.getResources().getDisplayMetrics(); 
    int mid = metrics.heightPixels/2 - edit_text.getHeight(); 

    ObjectAnimator positionAnimation = ObjectAnimator.ofFloat(edit_text, View.Y, mid); 
    positionAnimation.start(); 
} 
相關問題