使用objectAnimator在Android上移动视图,获得24dp(72p)偏移量

时间:2017-04-06 18:39:25

标签: android objectanimator

我正在尝试使用ObjectAnimator在android中移动一个按钮。我希望视图移动只是为了不与之前的位置重叠而不是更多。因此,当按下按钮时,我会计算新位置,例如new_location = Current_location_of_view + view_height。向上移动时:new_location = Current_location_of_view + view_height。但为了使其正常工作,我必须向上添加24dp(72p)偏移,我在获取当前视图的位置时减去72。这个偏移来自哪里? 我的猜测是view.getLocationOnScreen()函数的y轴起点与ObjectAnimator.ofFloat(view," y",new_location)函数不同,但我不知道为什么。该如何正确完成?

我正在使用此代码:

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???
}

1 个答案:

答案 0 :(得分:0)

我通过使用view.getY()而不是view.getLocationOnScreen()来解决问题。 getLocationOnScreen()函数返回的值比view.getY()多72px,我猜这个值是我的状态栏。我应该从头开始使用getY()函数,因为这是我在ObjectAnimator.ofFloat(view,“y”,newLocation)函数中使用的值。