user1561329
user1561329

Reputation: 89

How to add back button to WebView?

How do I make the back button go back to previous page/link history instead of closing the app?

Here's my code:

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

 if (keyCode == KeyEvent.KEYCODE_BACK){
  if(WebView.canGoBack()){
   WebView.goBack();
            return true;
  }
 }
 return super.onKeyDown(keyCode, event);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dsaif);
    runDialog(5);
    WebView engine = (WebView) findViewById(R.id.web_engine);
    engine.loadUrl("http://android.dsaif.tk/store/");
    engine.setWebViewClient( new HelloWebViewClient() );
} 

  private class HelloWebViewClient extends WebViewClient {

      @Override
      public boolean shouldOverrideUrlLoading( WebView view, String url ) {                 

         return false;
      }
  }

Sorry I'm very new to Android Development and know nothing about Java. Please provide full code :)

Upvotes: 0

Views: 1227

Answers (1)

Zyber
Zyber

Reputation: 1034

As mentioned by Kostas you create a button in your xml and then in the callback you call webview.goBack();

xml:

<Button
    android:id="@+id/backBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back  />

activity:

Button backButton = (Button) findViewById(R.id.backBtn);
backButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        engine.goBack();
    }
});

Edit:

This will make the phones back button to go back in history, if there is a history.

public class someNameHere extends Activity{
   private WebView engine;

   @Override
   public void onCreate(...){
       ...
       engine = (WebView) findViewById(R.id.web_engine);
       ...
   }
   @Override
   public boolean onKeyDown(...){
      if((keyCode == KeyEvent.KEYCODE_BACK) && engine.canGoBack()){
         engine.goBack();
         return true;
      }
      ...
   }

Upvotes: 1

Related Questions