sacheie
sacheie

Reputation: 768

Android app (embedded WebView) crashes when forcing landscape orientation

I have an HTML5 app, almost all of which takes place in Canvas. In the JS, I've set exact dimensions for the height and width of the canvas. I've also used a lot of absolute positioning with magic numbers to make the layout perfect. Note: everything is designed around landscape orientation and portrait isn't an option.

Running this in modern versions of Chrome, everything works great - Chrome seems to scale the canvas properly when the page loads (regardless of viewport size), and the absolutely positioned canvas drawing / HTML elements' positions scale accordingly.

But now I'm trying to accomplish the same thing with an Android app - very simple app that just loads a WebView, without anything containing it. The canvas is much smaller than the phone's resolution, so I'd imagine this should work.

My specific problem is that setting android:screenOrientation="landscape" in the Manifest file always makes the app crash immediately. My guess is that it's interacting badly with my main layout file, but I can't figure out how. I'm testing on a Samsung Galaxy S6, and building the app to SDK version 21.

What I want is behavior like I get in a desktop Chrome browser, but I can't seem to find a way that either fails to display the entire HTML5 Canvas, or crashes the app immediately.

Here is the JS I am using to position the canvas, which (in desktop Chrome) works - note that canvas#board is the canvas element.

<meta name='viewport' content='width=device-width, initial-scale=1'>

// some irrelevant code omitted...

var XRES  = 640;
var YRES  = 280;
var X_OFF = (window.innerWidth  - XRES) / 2;
var Y_OFF = (window.innerHeight - YRES) / 2;

// some irrelevant code omitted...

$('#board').css('left', X_OFF);
$('#board').css('top',  Y_OFF);
$('#submitDialog').css('left', X_OFF + 222);
$('#submitDialog').css('top',  Y_OFF +  41);

This centers the canvas in both dimensions regardless of the full viewport size, and centers the submitDialog (a div that is eventually used to submit high scores).

What I would like is a way to change either the HTML/JS, or the Android project configuration to achieve the same thing. The ideal is that I could make the WebView automatically scale to say 90% of the screen size. Any thoughts? My thanks in advance!

Upvotes: 1

Views: 501

Answers (1)

sacheie
sacheie

Reputation: 768

I found the answer. I was never able to make it work via the Manifest orientation=landscape property, but using setRequestedOrientation() in onCreate() works perfectly. I also had to set the WebView dimensions to the exact size the JS sets the Canvas element.

There were a few problems with scale and offset, easily solved by adjusting the scale and margin properties of the WebView (again with magic numbers, but I am sure the right values for any device could be computed and set in onCreate().

Upvotes: 1

Related Questions