Issue
I am trying to get width and height of my view during app initialization using onSizeChanged() of view, but it always return 0. I have read many questions here, but none of it worked, I always just get 0.
In my app, I have a canvas whose size I need to pass to another object which uses it to calculations. In canvas, I have variables width
a height
to store the size, and during initialization in MyActivity they are passed to that calculations. Problem is, it always returns 0, even when I've tried using getWidth() and getHeight().
I've also tried to retrieve the size in onResume(), but it seems that onSizeChanged() of my canvas still hasn't been called.
Snippet from MainActivity
@Override
protected void onResume() {
super.onResume();
hB = canvas.getW();
vB = canvas.getH();
ap = new ActualPosition();
generator = new PositionGenerator(ap);
table = new DrawTable(ap, hB, vB);
generator.runMe();
}
Code from canvas
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
this.w = w;
this.h = h;
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
}
public int getW() {
return w;
}
public int getH() {
return h;
}
So I would like to know when the onSizeChanged() method is called during Activity lifecycle.
Solution
You can use getViewTreeObserver()
method that is called just before the view is displayed.
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// prevent multiple calls by removing the listener
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
grid.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
grid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
int mWidth = yourView.getWidth();
int mHeight = yourView.getHeight();
}
}
});
Answered By - Pahomi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.