How to retrieve the dimensions of a view?

前端 未结 16 1668
小蘑菇
小蘑菇 2020-11-22 01:09

I have a view made up of TableLayout, TableRow and TextView. I want it to look like a grid. I need to get the height and width of this grid. The methods

16条回答
  •  孤独总比滥情好
    2020-11-22 01:25

    Even though the proposed solution works, it might not be the best solution for every case because based on the documentation for ViewTreeObserver.OnGlobalLayoutListener

    Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

    which means it gets called many times and not always the view is measured (it has its height and width determined)

    An alternative is to use ViewTreeObserver.OnPreDrawListener which gets called only when the view is ready to be drawn and has all of its measurements.

    final TextView tv = (TextView)findViewById(R.id.image_test);
    ViewTreeObserver vto = tv.getViewTreeObserver();
    vto.addOnPreDrawListener(new OnPreDrawListener() {
    
        @Override
        public void onPreDraw() {
            tv.getViewTreeObserver().removeOnPreDrawListener(this);
            // Your view will have valid height and width at this point
            tv.getHeight();
            tv.getWidth();
        }
    
    });
    

提交回复
热议问题