简体   繁体   中英

Android WebView loads startpage when turning smartphone

I got this code (relevant part only):

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private int whichPage = 0;

    protected void onCreate(Bundle savedInstanceState) {
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(this.getString(whichPage == 0 ? R.string.vPlan : R.string.tPlan));
    }
}

In the OptionsMenu the user can change the page... Now my problem is that each time the user turns his/her phone it will load R.string.vPlan even if it was set to tPlan (and whichPage contained 1).

Is there a way to stop the app from jumping to vPlan or even stop it from loading a page at all?

Thank you.

When you turn the smartphone, the activity is being re-created and the variables are being re-initialized. So every time you rotate, the whichPage value is being set to 0 . You have two options:

1- You can use onSaveInstanceState() and onRestoreInstanceState() to save the activity state (the required variables which you want to keep track of even when user rotates). Checkout Saving Android Activity state using Save Instance State and Recreating an Activity .

2- Stop the activity from being recreated on rotating the device. However Google Engineers suggest against this way.

Hope it helps.

try this if it helps

public class MainActivity extends AppCompatActivity {
private WebView webView;
private int whichPage = 0;

protected void onCreate(Bundle savedInstanceState) {

if (savedInstanceState == null){

    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(this.getString(whichPage == 0 ? R.string.vPlan : R.string.tPlan));
} else {
    // do nothing
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM