Change URL at runtime in webview in android

2019-07-15 16:19发布

I have created a small program that will load particular website in webview. I want to keep watch on URL and if URL contains 'xxx' word then it should navigate to another page. for example if I set www.example.com. and I can now navigate to any page of www.example.com. If my Url contains word like 'xxx' then I want to exit that url and navigate to another url. Is is possible? and how? Thanks.

//Here is my code.
public class MainActivity extends Activity {
private WebView Browser;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Browser = (WebView) findViewById(R.id.webView1);


    Browser.setWebViewClient(new WebViewClient()
    {
        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("when you click on any interlink on webview that time you got url :-" + url);
            int len = url.length();
            if(url.contains("xxx"))
            {
                url = "http://www.example.com/xxxx";
                Toast.makeText(MainActivity.this, "URL changed.."+url, Toast.LENGTH_LONG).show();
            }    
            else
                Toast.makeText(MainActivity.this, "URL not changed.."+url, Toast.LENGTH_LONG).show();
            return super.shouldOverrideUrlLoading(view, url);
        }



    });

    Browser.getSettings().setLoadsImagesAutomatically(true);
    Browser.getSettings().setJavaScriptEnabled(true);
    Browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    Browser.loadUrl("http://www.example.com/");
    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

1条回答
▲ chillily
2楼-- · 2019-07-15 16:58

yes.. you can navigate webview runtime. Put your logic into onPageFinished() method of WebViewClient.

public void onPageFinished(WebView view, String url) {
    if (webView.getUrl().contains("xxx")) {
        URL = "http://www.example.com/xxxx";
        webView.loadUrl(URL);
    }
}
查看更多
登录 后发表回答