Android WebView在WebView中单击打开而不是默认浏览器?

时间:2013-07-26 03:05:19

标签: android android-webview

我使用WebView做了一个示例应用程序,在该Web视图中,URL来自Web服务。它工作正常,但如果我点击该WebView中的任何链接,它会自动转到默认的Web浏览器。但我想在我的应用程序Web视图中打开。这是我的代码:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String url ="http://www.cementegypt.com/m/";
        WebView view =(WebView) this.findViewById(R.id.webView1);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
    }
    @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;
    }

}

3 个答案:

答案 0 :(得分:10)

尝试:

WebView view =(WebView)findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});

来源:This通过@ momo回答非常相似的问题:Link should be open in same web view in Android。希望这会有所帮助。

答案 1 :(得分:0)

这是因为WebView.loadUrl仅用于查看WEBPAGE,而且似乎就像创建自己的浏览器一样,这是另一个问题。尝试使用这样的东西:

WebView w;    

w.setWebViewClient(new WebViewClient(){

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            return super.shouldOverrideUrlLoading(view, url);
        }

    });

答案 2 :(得分:0)

你应该覆盖WebViewClient类的shouldOverrideUrlLoading(),这里就像 -

    w.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) 
        {
            super.shouldOverrideUrlLoading(view, url);

            if(url!=null&&(URLUtil.isHttpsUrl(url)||URLUtil.isHttpUrl(url)))
            {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
return false;
}});