Issue
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();
}
Solution
A view still hasn't been drawn when onResume()
is called, so its width and height are 0. You can "catch" when its size changes using OnGlobalLayoutListener()
:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Removing layout listener to avoid multiple calls
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else {
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
populateData();
}
});
For additional info take a look at Android get width returns 0.
Answered By - Onik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.