在 Android 中绘制到屏幕之前读取 gui 元素的大小

Reading size of a gui element before it is drawn to the screen in Android

我正在为 android 开发,我需要在将 gui 元素绘制到屏幕之前读取它的最终宽度和高度。有那个功能吗?

尺寸只有在测量视图后才能知道。如果您想尽早了解其大小,可以使用 ViewTreeObserver。

private View view; // the view whose size you want to know

public void onCreate(Bundle savedInstanceSatet) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.whatever);
    view = findViewById(...);

    final ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressLint("NewApi")
        @Override
        public void onGlobalLayout() {
            // if you only need the size once, unregister this listener
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                observer.removeOnGlobalLayoutListener(this);
            } else {
                observer.removeGlobalOnLayoutListener(this);
            }

            // here you can call view.getWidth() and view.getHeight()
        }
    });
    ...
}

或者,如果您的视图是自定义视图,您可以覆盖 onSizeChanged()