Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load webview links inside this same webview Android

I want to build a Android webApplication without PhoneGap, and i have a problem : when i click on a link it open the android default browser... : so how to load webview links inside this same webview Android ?

Here is my code :

package com.example.mobilewebview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
//import android.webkit.WebViewClient;
import android.webkit.WebSettings;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://m.google.com");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Thanks !

like image 752
Random78952 Avatar asked Oct 22 '25 16:10

Random78952


1 Answers

You have to intercept the URL links that your WebView might have in order to do your custom implementation.

You have to create a WebViewClient for your WebView and then override the public boolean shouldOverrideUrlLoading(WebView view, String url) method to achieve such a thing.

Sample code:

//web view client implementation
private class CustomWebViewClient extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) 
    {
        //do whatever you want with the url that is clicked inside the webview.
        //for example tell the webview to load that url.
        view.loadUrl(url);
        //return true if this method handled the link event
        //or false otherwise
        return true;
    }
}}

//in initialization of the webview:
....
webview.setWebViewClient(new CustomWebViewClient());
....

Tell me if that helps.

like image 99
10s Avatar answered Oct 24 '25 06:10

10s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!