I am writing a small game and I want the game canvas to keep its proportions and always be in landscape orientation. So I have a code like this:
activity_game.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#Ff0000" <!-- red -->
tools:context=".EngineActivity">
<com.example.arsen.pw3.game.GameLayout
android:id="@+id/mainWrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00Ff00" <!-- green -->
android:gravity="center">
<!-- canvas and all additional stuff comes here -->
</com.example.arsen.pw3.game.GameLayout>
</RelativeLayout>
GameLayout.java:
public class GameLayout extends RelativeLayout {
public GameLayout(Context context) {
super(context);
}
public GameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// overriding onSizeChanged to take care that the proportions will be kept.
@Override
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
double ratio;
double canvasRatio = width / (double) height;
GameSettings.DisplaySize displaySize = GameSettings.getInstance().displaySize;
double gameDisplayRatio = displaySize.height / displaySize.width;
if(canvasRatio > gameDisplayRatio) {
ratio = width / displaySize.width;
} else {
ratio = height / displaySize.height;
}
getLayoutParams().height = (int) (ratio * displaySize.height);
getLayoutParams().width = (int) (ratio * displaySize.width);
}
}
It works properly until I return to application after switching to other.
This is how it looks when I run the app, but once I open the system switcher and then return to it, it looks like this.
So it looks that the width and height I get in onSizeChanged() method is the one from before the landscape orientation is set, and for some reason the method is not called again with the right width once the orientation is changed.
What am I doing wrong here?