开发者

Programmatically getting the width of a TextView

I'm attempting to build a layout programmatically.

This layout is dynamic. Based on the data read from a database, it could look different every time.

I have a LinearLayout with its orientation set to vertical.

I want to fit as many TextViews开发者_StackOverflow社区 with text (the data from database) as I can on a "row".

What I'm doing is building LinearLayouts that are the rows. These LinearLayouts are populated with TextViews. I build the TextView, set the text, and then check the width to see if it will fit on this row (by subtracting the sum of all TextView widths from the screen width and see if the new TextView will fit). If not, I create a new LinearLayout and start adding TextViews to that one.

The problem is myTextView.getWidth() and myTextView.getMeasuredWidth() both return 0.

Why? How can I get the width of the TextView?


Well first of all, please post your code. Second the getWidth/getHeight returning zero question gets asked A LOT so you could search SO for more answers.

Assuming your calling these methods during onCreate (which is probably the case), the UI hasn't been drawn yet so the returned value is zero. You can't get the width or height of the view until it has been drawn.


You can use this library to schedule the task of perform calculation on the width to the correct time after the view had been completely drawn

You can call it on onCreate() and from any Thread

https://github.com/Mohamed-Fadel/MainThreadScheduler

Sample of use:

MainThreadScheduler.scheduleWhenIdle(new Runnable() {
       @Override
       public void run() {
           int width = textview.getWidth();
           int height = textview.getHeight();
           textview.setText( String.valueOf( width +","+ height ));
       }
   });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜