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

时间:2015-04-24 16:38:15

标签: android user-interface size

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

1 个答案:

答案 0 :(得分:0)

The size is only known after the view has been measured. If you want to find out about its size as early as possible, you can use a 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()
        }
    });
    ...
}

Alternatively, if your view is a custom View, you can override onSizeChanged()