This is the solution I came up with. If someone has different or better, please post it.
Since the problem only exists in 4.4.2 (and future, I assume), I used an if and the SDK_INT
to do something different for 19 and greater. The issue appears to be that images don't have a height and width until displayed, and in 4.4.2 sometimes for a short time after it is displayed the getWidth()
and getHeight()
functions will still return 0. However, assuming I am doing no scaling on the image, I can use the getBackground().getIntrinsicHeight()
and getBackground().getIntrinsicWidth()
and use that instead. To get the screen width and height I used getSize(point)
on the Display, and since I'm using the screen size and not the size of the Relative View I need to get the padding of the parent in order to center it properly.
LayoutParams params = (LayoutParams) mMenuButton.getLayoutParams();
if (android.os.Build.VERSION.SDK_INT >= 19) {
RelativeLayout mButtonsLayout = (RelativeLayout) getParent();
WindowManager wm = (WindowManager) mcontext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
params.topMargin = (size.y - mMenuButton.getBackground().getIntrinsicHeight()) / 2 - mButtonsLayout.getPaddingTop();
params.leftMargin = (size.x - mMenuButton.getBackground().getIntrinsicWidth()) / 2;
}
else {
params.topMargin = (getHeight() - mMenuButton.getHeight()) / 2;
params.leftMargin = (getWidth() - mMenuButton.getWidth()) / 2;
}
mMenuButton.setLayoutParams(params);
There is probably a better solution out there, and I hope someone posts it, but this solution is working for me at the moment.