Ali Ali - 4 years ago 136
Android Question

Keep webview while changing layout on screen rotation

My app have two different layout for portrait and landscape mode which both encapsulate a webview and some buttons. Buttons are at bottom in portrait and at left in landscape so more reading space is available in webview.

The problem is, the activity is recreated on screen rotation and webview loads the first page which is not a wanted behavior.

I searched and found out using android:configChanges="orientation" in activity tag prevents recreating of the activity. But the porblem is it prevents the layout changing too as it happens in activity creation.

I want my program to work in 2.2, waht's the best way to this?

Ali Ali
Answer Source

I tested fragments, but dealing with fragment makes things much more complex and the fragment itself needs saving and restoring which may not work in a webview which has javascript state, So I searched more and find a nice article somewhere and with some modification I came to a solution which I suggest:

First, add android:configChanges="orientation|screenSize|keyboard|keyboardHidden" to manifest so app handles the config change instead of android.

Make two different layout for lnadscape and portrait mode and put them in corresponding layout folders. In both layouts instead of webview place a LinerLayout which acts as a placeholder for webview.

In code define initUI method like this and put every thing related to UI initialization in this method:

public void initui()
    if (wv == null) wv = new WebView(this);

If the webview doesn't exist, it will be created and after setContentView(R.layout.main) it will be added to the layout. Other UI customization came afterward.

and in onConfigurationChanged:

public void onConfigurationChanged(Configuration newConfig)

In onConfigChange First the webview is removed from old place holder and initui will be called which will add it back to the new layout.

and in oncreate call initui so the ui will be initialized for the first time.

public void onCreate(Bundle savedInstanceState)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download