In Android how to get the width of the Textview which is set to Wrap_Content

前端 未结 8 1644
时光取名叫无心
时光取名叫无心 2020-12-11 03:56

I am trying to add a text to the textview for which i have set the width as Wrap_content. I am trying to get the width of this textview. But its showing 0 in all the cases.

相关标签:
8条回答
  • 2020-12-11 04:22

    When are you calling this? Has it already been drawn to the screen?

    It sounds like you are calling getWidth() too early.

    You can also take a look at this question.

    0 讨论(0)
  • 2020-12-11 04:25

    you can try this:

    textView.measure(0,0);
    int width = textView.getMeasuredWidth();
    
    0 讨论(0)
  • 2020-12-11 04:27

    You can not get the width of a View with dynamic size before the layout is completely built. That means there is no way you can get it in onCreate(). One way would be to create a class that inherits from TextView and overrides onSizeChanged().

    0 讨论(0)
  • 2020-12-11 04:28

    this works for me:

    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 讨论(0)
  • 2020-12-11 04:32

    hello use this method:

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

    });

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

    0 讨论(0)
  • 2020-12-11 04:39

    Views with the dynamic width/height get their correct size only after a layout process was finished (http://developer.android.com/reference/android/view/View.html#Layout).
    You can add OnLayoutChangeListener to your TextView and get it's 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);                
        });
    
    0 讨论(0)
提交回复
热议问题