开发者

How can I programatically get two different table's 'cells' to have the same width in Android?

开发者 https://www.devze.com 2023-03-28 16:19 出处:网络
I have two TableLayout widgets, created programaticallyin my Activity\'s onCreate() method. Table1: SomeTextCell1SomeReallyReallyLongTextCell2SomeTextCell3

I have two TableLayout widgets, created programatically in my Activity's onCreate() method.

Table1:
SomeTextCell1  SomeReallyReallyLongTextCell2  SomeTextCell3

Table2:
SomeOtherTextCell1  ShortText开发者_如何学CCell2  SomeOtherTextCell3

Table1 is displayed directly above Table2.

I'm looking for a way to programatically assign the width of Table1's and Table2's cells (which are TextView widgets added to a TableRow) to be the same as the widest in that column (as the text in each cell can be a number of different values). Is this possible? Something like this:

Table1:
SomeTextCell1       SomeReallyReallyLongTextCell2  SomeTextCell3

Table2:
SomeOtherTextCell1  ShortTextCell2                 SomeOtherTextCell3

Getting the width in the onCreate() method of these TextView widgets just returns 0 which kinda makes sense as the UI hasn't laid out anything yet. Is there an activity hook I can use once the layout is complete and myTextViewWidget.getWidth() will return a non-zero value?


OK, so finally solved this one. This answer was the key. Essentially, you attach a global layout listener to the view you are interested in (the parent of Table1 and Table2 in my case) and implement the listeners onGlobalLayout() method. This gets invoked once after layout is complete allowing getWidth() and getHeight() to work. The rest of the solution was simple (if a bit ugly) which involved determining the maximum width of a column across the tables and then looping through the table rows and setting the column widths to the maximum column width. Worked a charm!

Special thanks to kcoppock for his excellent solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消