简体   繁体   中英

Stop Android back button from restarting Activity

I am making an app that loads a webview for the main content. I have a menu inflater that will provide a few links. I'm using the menu inflater as a warning label. "Are you sure you want to leave this page?" But if the user doesn't want to leave this page I want them to be able to press the back button to return to the webview. The problem I'm having is that the back button restarts the activity and reloads the web page.

I tried sending my savedContentState in a bundle to the menu class but I have no idea how to apply it to my webview when I push the back button.

Main Class:

protected void onRestoreInstanceState(Bundle savedInstanceState) {

    super.onRestoreInstanceState(savedInstanceState);
    web.restoreState(savedInstanceState);
    Intent in = new Intent(getApplicationContext(), DBZWiki.class);
    in.putExtras(savedInstanceState);
    startActivity(in);
}


public boolean onCreateOptionsMenu(android.view.Menu menu) {

    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.dbz_menu, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case R.id.dbzAbout:
        break;

    case R.id.dbzDonate:
        break;

    case R.id.dbzWiki:
        Intent a = new Intent("com.example.thenewboston.DBZWIKI");
        startActivity(a);

        break;
    }
    return false;
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    web.loadUrl("file:///android_asset/infAppPaused.html");

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    web.loadUrl(stream);
}

}

Wiki Menu Class :

public class DBZWiki extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dbz_wiki);

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if(keyCode == KeyEvent.KEYCODE_BACK) {
        Intent in = getIntent();
        startActivity(in);
    }
    return true;
}

I solved the problem. Pressing the back button called onResume().

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
web.loadUrl(stream);
}

So loadUrl was making the webView reload, not the activity restarting.

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