在不创建自定义视图的情况下查找视图的中心

Find center of a view without creating a custom view

这确实是一项非常简单的任务,但我看过的所有解决方案似乎都指向我创建一个扩展 imageview 的自定义视图。坦率地说,这很荒谬。这是我想要做的:

我的动画:

public void spin() {

    float centerX = imageview.getX() + (imageview.getWidth()/2);
    float centerY = imageview.getY() + (imageview.getHeight()/2);

    Animation animation = new RotateAnimation(0, 360, centerX, centerY);
    animation.setRepeatCount(Animation.INFINITE);

    imageview.setAnimation(animation);
    imageview.animate();

}

我的看法:

<ImageView
    android:id="@+id/imageview"
    android:src="@mipmap/app_icon"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/progressbar"
    android:layout_marginBottom="60dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

在片段生命周期的每个阶段(onCreateView、onStart、onResume 和 onActivityCreated),getX()、getY()、getWidth() 和 getHeight() 全部 return 0。

是否可以在不创建自定义视图的情况下获得我的视图中心?

尝试在 Fragment 生命周期方法中获取 View's 维度不是正确的方法。最简单的方法是使用 ViewTreeObserver,像这样:

mYourImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
       int width = mYourImageView.getWidth();
       int height = mYourImageView.getHeight();
        if (width > 0 && height > 0) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
              mYourImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
              mYourImageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }

            //now you've got your dimensions.

        }
    }
});