2017-04-06 25 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)函数中使用的值。