在一个额外的WebView类中启动intent而不是在内部类中?

时间:2017-03-23 08:20:47

标签: java android android-intent android-webview

我想保持我的MainActivity小而清晰。所以我用这种方式为WebView 而不是内部类创建了一个单独的类

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
    mWebView.setWebViewClient(new CustomWebViewClient()); 

但现在我想使用CustomWebViewClient方法在openInAppBrowser开始一项新活动:

public class CustomWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith(PROJECT_REMOTE)) {
            return false;
        } else {
            openInAppBrowser(this, url);
        }
        return true;
    }
    private void openInAppBrowser(Activity activity, String url) {
        Intent intent = new Intent(activity, InAppBrowser.class);
        intent.putExtra("url", url);
        activity.startActivity(intent);
    }

由于thisMainActivity.this在这里不起作用,我如何引用MainActivity以使此方法有效?或者MainActivity中的内部类是更好还是唯一的选择?

1 个答案:

答案 0 :(得分:2)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
    mWebView.setWebViewClient(new CustomWebViewClient(this)); 



public class CustomWebViewClient extends WebViewClient {

Activity activity;

public CustomWebViewClient (Activity activity) {
    this.activity= activity;

}

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith(PROJECT_REMOTE)) {
            return false;
        } else {
            openInAppBrowser(url);
        }
        return true;
    }
    private void openInAppBrowser(String url) {
        Intent intent = new Intent(activity, InAppBrowser.class);
        intent.putExtra("url", url);
        activity.startActivity(intent);
    }

根据要求。我不确定这会起作用,这就是为什么我首先没有回答。