如何在webview中打开除定义的URL之外的URL?

时间:2016-10-07 08:08:55

标签: android android-layout android-studio webview android-webview

我尽我所能,但它对我不起作用。我想在默认浏览器中打开http://google.com以外的网址。应该添加什么代码,我看到了android文档并添加了代码,但它不起作用。任何建议都表示赞赏。

public class MainActivity extends Activity {

  
    private WebView webview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        this.webview = (WebView) findViewById(R.id.activity_main_webview);
        webview.loadUrl("http://google.com");
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 

        webview.setWebViewClient(new WebViewClient()

        {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                }
});

 }

 }

2 个答案:

答案 0 :(得分:0)

尝试此代码段并确保您在清单文件中具有Internet权限

 public class MainActivity extends Activity {


        private WebView webview;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            webview = (WebView) findViewById(R.id.activity_main_webview);
            getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            webview.loadUrl("http://google.com/");

            webview.getSettings().setJavaScriptEnabled(true);

 webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
               String myAlternativeURL = "http://yahoo.com";
    if (!url.equals(myAlternativeURL)) {
        view.loadUrl(myAlternativeURL);
        return true;
    }
                }
});
 });

答案 1 :(得分:0)

你可以尝试这个希望,这可以帮助你..

public class MainActivity extends AppCompatActivity {

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.tv);

    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Uri uri = Uri.parse("http://gmail.com");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });
}

}