On Android, how to get the width of the Textview that is set to Wrap_Content

I am trying to add text to a text view for which I set the width as Wrap_content. I am trying to get the width of this text. But its mapping is 0 in all cases. How can I get the width of the text field after setting the text in it.

the code looks like this:

        LinearLayout ll= new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        ll.addView(tv);
        tv.setText("Hello 1234567890-0987654321qwertyuio787888888888888888888888888888888888888888888888888");
        System.out.println("The width is == "+tv.getWidth());// result is 0
        this.setContentView(ll);

Please offer. Thanks in advance.

+5
source share
8 answers

Views with dynamic width / height get their correct size only after the layout process is complete ( http://developer.android.com/reference/android/view/View.html#Layout ).
You can add OnLayoutChangeListener to your TextView and get its size there:

tv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
           public void onLayoutChange(View v, int left, int top, int right, int bottom, 
                                      int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        final int width = right - left;
                        System.out.println("The width is == " + width);                
    });
+7

, . , onCreate(). , TextView onSizeChanged().

+2

? ?

, getWidth().

.

+1

:

RelativeLayout.LayoutParams mTextViewLayoutParams = (RelativeLayout.LayoutParams) mTextView.getLayoutParams();
mTextView.setText(R.string.text);
mTextView.measure(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
int width = mShareTip.getMeasuredWidth();
//use the width to do what you want
mShareTip.setLayoutParams(mShareTipLayoutParams);
0

:

textView.measure(0,0);
int width = textView.getMeasuredWidth();
0

, :

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

});

: https://gist.github.com/omorandi/59e8b06a6e81d4b8364f

0

You can use this library to schedule the task of calculating the width to the desired time after the full drawing of the image

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

Usage example:

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

You should use this:

textView.getMeasuredWidth ();

-1
source

All Articles