How can you tell when a layout has been drawn?

后端 未结 8 531
轻奢々
轻奢々 2020-11-22 08:07

I have a custom view that draws a scrollable bitmap to the screen. In order to initialize it, i need to pass in the size in pixels of the parent layout object. But during th

8条回答
  •  -上瘾入骨i
    2020-11-22 08:33

    You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

        final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
        ViewTreeObserver vto = layout.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
            @Override 
            public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        layout.getViewTreeObserver()
                                .removeOnGlobalLayoutListener(this);
                    } else {
                        layout.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                int width  = layout.getMeasuredWidth();
                int height = layout.getMeasuredHeight(); 
    
            } 
        });
    

提交回复
热议问题