replace layout on orientation change

android, android-layout

Solution

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"` so the app handles the config changes instead of android.

Make two different layout for landscape and portrait. In both layouts instead of webview place a FrameLayout which acts as a placeholder for the webview.

Define initUI method like this and put everything related to UI initialization in this method:

public void initui()
{
    setContentView(R.layout.main);
    if (wv == null) wv = new WebView(this);
    ((LinearLayout)findViewById(R.id.webviewPlace)).addView(wv);
    findViewById(R.id.home).setOnClickListener(this);
}

If the webview doesn't exist yet it will be created and after `setContentView(R.layout.main)` it will be added to the layout. Any other UI customization you need came after this.

and in `onConfigurationChanged`:

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    ((LinearLayout)findViewById(R.id.webviewPlace)).removeAllViews();
    super.onConfigurationChanged(newConfig);
    initUI();
}

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

In `oncreate()` call `initui()` so the ui will be initialized for the first time.

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    initUI()
}

I wish it would be helpful for someone.

Problem

My app has a webview and some buttons inside a LinerLayout. the problem is, I want the buttons to be on bottom in portrait mode and on left in landscape mode while the webview maintains it's state. Two different layout doesn't work as it force recreation of the activity that refresh the webview. for now I use android:configChanges="orientation" in activity tag so webview doesn't get refreshed on orientation change. Is there anyway to replace the layout of buttons on the change of screen mode? portrait mode landscape mode

Original source

Related problems