Get the height of a TextView

前端 未结 2 1661
闹比i
闹比i 2021-02-09 18:03

I have some text that will be put in a TextView. I did that using setText().

Now I need to find the number of lines or height the text occupies

2条回答
  •  臣服心动
    2021-02-09 18:34

    Because this size is known only after the layout is finished, one way is to create a custom text view and use onSizeChanged method. Another way is this:

        final TextView tv = (TextView) findViewById(R.id.myTextView);
        ViewTreeObserver vto = tv.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @Override 
            public void onGlobalLayout() { 
                Toast.makeText(MyActivity.this, tv.getWidth() + " x " + tv.getHeight(), Toast.LENGTH_LONG).show();
                tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } 
        }); 
    

    This code I've found here: How to retrieve the dimensions of a view?

提交回复
热议问题