简体   繁体   中英

Can't get height of Widgets

I am facing a problem when gets height/width of TextView.

My code :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv1 = (TextView)findViewById(R.id.textview1);
    int h1 = tv1.getHeight();
    TextView tv2 = (TextView)findViewById(R.id.textview2);
    int h2 = tv2.getHeight();
}

h1 is height of textview1 h2 is height of textview2

These h1 and h2 are always equal to 0.

What is wrong here ?

Please advice.

Thanks.

View.getWidth()/View.getHeight() won't give you a meaningful answer until the view has been measured. Read about how android draws views here.
See this thread to get an idea of when the measured dimensions will be available.

tv1.getHeight() will return 0 (as well as tv2.getWidth()) if it's not drawed yet.

Solution would be to get the height after your view is layouted:

tv1.post(new Runnable(){
    public void run(){
         int height = tv1.getHeight();
    }
});
tv2.post(new Runnable(){
    public void run(){
         int height = tv2.getHeight();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM