Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

android - Why does calling getWidth() on a View in onResume() return 0?

Everything I've read says you can't call getWidth() or getHeight() on a View in a constructor, but I'm calling them in onResume(). Shouldn't the screen's layout have been drawn by then?

@Override
protected void onResume() {
    super.onResume();

    populateData();
}

private void populateData() {
    LinearLayout test = (LinearLayout) findViewById(R.id.myview);
    double widthpx = test.getWidth();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you have to wait that the the current view's hierarchy is at least measured before getWidth and getHeigth return something != 0. What you could do is to retrieve the "root" layout and post a runnable. Inside the runnable you should be able to retrieve width and height successfully

root.post(new Runnable() {
     public void run() {
         LinearLayout test = (LinearLayout) findViewById(R.id.myview);
         double widthpx = test.getWidth();
     }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...