2017-04-06 26 views
0

我正在嘗試使用ObjectAnimator在android中移動按鈕。我希望視圖能夠移動,以便它不會與前一個位置重疊,也不會重疊。所以,當按下按鈕時,我計算新的位置,如new_location = Current_location_of_view + view_height。當移動時:new_location = Current_location_of_view + view_height。但爲了正常工作,我必須向上添加24dp(72p)的偏移量,在獲取當前視圖的位置時,通過減去72來實現此目的。這個抵消來自哪裏? 我的猜測是view.getLocationOnScreen()函數與ObjectAnimator.ofFloat(view,「y」,new_location)函數有不同的y軸起點,但我不知道爲什麼。這應該如何正確完成?使用objectAnimator在Android上移動視圖,獲得24dp(72p)的偏移量

我使用這個代碼:

private void moveViewUpMinimum(View view, int viewHeight){ 
    int currentViewLocation = getViewLocation(view); 
    Log.e("Actual location", String.valueOf(currentViewLocation)); 
    if(currentViewLocation >viewHeight){ 
     //if there is enough space on top of the screen 
     ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "y", currentViewLocation-viewHeight); 
     Log.e("Set location:", String.valueOf(currentViewLocation-viewHeight)); 
     objectAnimator.setDuration(100); 
     objectAnimator.start(); 
    } 
    else{ 
     //if no more room move the view down 
     ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "y", screenHeight-viewHeight); 
     objectAnimator.setDuration(100); 
     objectAnimator.start(); 
    } 
} 
private void moveViewDownMinimum(View view, int viewHeight){ 
    int currentViewLocation = getViewLocation(view); 
    Log.e("Actual location", String.valueOf(currentViewLocation)); 
    if(screenHeight - currentViewLocation >= 2*viewHeight){ 
     //if there is enough space on the bottom of the screen 
     ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "y", currentViewLocation+viewHeight); 
     Log.e("Set location:", String.valueOf(currentViewLocation+viewHeight)); 
     objectAnimator.setDuration(100); 
     objectAnimator.start(); 
    } 
    else{ 
     //if no more room move the view up 
     ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "y", 0); 
     objectAnimator.setDuration(100); 
     objectAnimator.start(); 
    } 
} 
private int getViewLocation(View view){ 
    int buttonLoc[] = {0, 0}; 
    view.getLocationOnScreen(buttonLoc); 
    return buttonLoc[1]-72;//where does this offset come from??? 
} 

回答

0

我固定通過使用view.getY(問題)而不是view.getLocationOnScreen()。 getLocationOnScreen()函數返回的值比view.getY()多72px,我猜這個值是我的狀態欄。我應該從一開始就使用getY()函數,因爲這是我在ObjectAnimator.ofFloat(view,「y」,newLocation)函數中使用的值。