我正在尝试将WebViewClient添加到我的WebView应用程序中。但是每次我尝试使用WebViewClient启动它时,它都会停止工作。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyWebViewClient webViewClient = new MyWebViewClient(this);
myWebView.setWebViewClient(webViewClient);
myWebView = findViewById(R.id.webview);
myWebView.loadUrl("https://www.google.com.br/");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
MyWebViewClient.java
public class MyWebViewClient extends WebViewClient {
private Activity activity = null;
public MyWebViewClient(Activity activity) {
this.activity = activity;
}
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if(url.contains("https://google.com/")) return false;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
}
当我在 MainActivity.java 中的行myWebView.setWebViewClient(webViewClient);
上注释时,该应用程序将再次运行。关于如何解决此WebVIewClient问题的任何想法?
答案 0 :(得分:0)
在这里,您要在myWebView
之前设置客户端
初始化。
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//should be initialized first
myWebView = findViewById(R.id.webview);
MyWebViewClient webViewClient = new MyWebViewClient(this);
myWebView.setWebViewClient(webViewClient);
myWebView.loadUrl("https://www.google.com.br/");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}