3

I have set TextViews in a linear layout using layout weights.

   linearLayout.setWeightSum(7f);

   for(int i=0;i<7;i++){
     TextView tv= new TextView(this);
     tv.setLayoutParams(new LinearLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, 0, 1f));
     tv.setText("sometext");
     linearLayout.addView(tv);
   }

How do I get the width and height of these TextViews after the layout is drawn?

tv.getWidth() and tv.getHeight() return 0;

nette
  • 575
  • 2
  • 8
  • 25
  • Possible duplicate of [View's getWidth() and getHeight() returns 0](https://stackoverflow.com/questions/3591784/views-getwidth-and-getheight-returns-0) – Dan Mar 18 '18 at 17:26
  • If anyone else comes across this problem and is after a quicker way to do this, there are several options on this [answer](https://stackoverflow.com/a/24035591/4601149) – Dan Mar 18 '18 at 17:28

2 Answers2

10

Use

getViewTreeObserver

as

 yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // get size of view here
        }
    });
Amarjit
  • 4,327
  • 2
  • 34
  • 51
-1

Try Following

TextView mLblDesc=(TextView)findViewById(R.id.mLblDesc);
        mLblDesc.getMaxHeight();
        mLblDesc.getMaxWidth();
Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39