使用动画动态更改视图的 X、Y android

Change X,Y of view dynamically with animation android

我正在使用 CursorWheelLayout 库并且在适配器中我为每个按钮创建了一个视图,现在我想将每个按钮移动到中心按钮并使其消失但由于某种原因它永远无法正常工作...这是我正在使用的代码

private void startInvsibleAnimation(View view){
    //get the x and y i want the view to go to
    int[] location = new int[2];
    centerItem.getLocationOnScreen(location);
    int x = location[0];
    int y = location[1];
    Log.d("Debug","Center Item X: "+x+" Center Item Y: "+y);
    TranslateAnimation anim = new TranslateAnimation(0, x, 0, y);
    anim.setDuration(1000);
    anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) { }
        @Override
        public void onAnimationRepeat(Animation animation) { }
        @Override
        public void onAnimationEnd(Animation animation)
        {
            int[] location3 = new int[2];
            view.getLocationOnScreen(location3);
            int x2 = location3[0];
            int y2 = location3[1];
            Log.d("Debug","After Animation X: "+x2+" After Animation Y: "+y2);
        }
    });
    view.startAnimation(anim);
}

我用过这个代码:

    private void startInvsibleAnimation(View view){
    //get the x and y i want the view to go to
    int[] location = new int[2];
    centerItem.getLocationOnScreen(location);
    int x = location[0];
    int y = location[1];
    Log.d("Debug","Center Item X: "+x+" Center Item Y: "+y);
    view.animate().translationY(y);
    view.animate().translationX(x);
}

动画从不工作看到底部按钮总是向下但应该向上因为中心项目在视图上方所以问题是什么?

结果:

https://imgur.com/a/EQ3IYYr

您需要找到 view 位置和 centerItem 位置之间的差异,然后通过设置翻译将该差异应用到 view

 private void startInvsibleAnimation(View view){
    //get the x and y i want the view to go to
    int[] location = new int[2];
    centerItem.getLocationOnScreen(location);

    int translationX = location[0] - view.getX();
    int translationY = location[1] - view.getY();
    
    view.animate().translationX(translationX ).translationY(translationY);    
}