How to retrieve the dimensions of a view?

前端 未结 16 1644
小蘑菇
小蘑菇 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:30

    ViewTreeObserver and onWindowFocusChanged() are not so necessary at all.

    If you inflate the TextView as layout and/or put some content in it and set LayoutParams then you can use getMeasuredHeight() and getMeasuredWidth().

    BUT you have to be careful with LinearLayouts (maybe also other ViewGroups). The issue there is, that you can get the width and height after onWindowFocusChanged() but if you try to add some views in it, then you can't get that information until everything have been drawn. I was trying to add multiple TextViews to LinearLayouts to mimic a FlowLayout (wrapping style) and so couldn't use Listeners. Once the process is started, it should continue synchronously. So in such case, you might want to keep the width in a variable to use it later, as during adding views to layout, you might need it.

提交回复
热议问题