Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

android - replace layout on orientation change

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?

enter image description here

portrait mode

enter image description here

landscape mode

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...