在Web视图中为特定链接设置onclick事件

8

我有一个webview,从webservice中调用其中的数据,在webview中,整个描述中有一个链接。我的问题是,我只想在单击该链接时打开一个新活动,而不是单击webview或触摸webview。

1个回答

17

你需要为shouldOverrideUrlLoading提供实现。你将需要为你的webview设置一个WebViewClient,在这个方法中,你需要编写一些逻辑来识别这个链接并打开新的Activity。例如:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wv = (WebView) findViewById(R.id.myWebView);
        wv.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(isURLMatching(url)) {
                    openNextActivity();
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }

    protected boolean isURLMatching(String url) {
            // some logic to match the URL would be safe to have here
        return true;
    }

    protected void openNextActivity() {
        Intent intent = new Intent(this, MyNextActivity.class);
        startActivity(intent);
    }

1
shouldOverrideUrlLoading已被弃用。 - Amar Ilindra
1
@AmarIlindra,但你可以使用该方法的不同签名。 - Rohan Pawar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接