我在Android中有一个Web视图,我在其中打开一个html网页。但它充满了链接和图像,当我点击其中一个时,它会加载到我的网页视图中。所以我想禁用此行为,因此如果我点击链接,请不要加载它。我已经尝试过这个解决方案并为自己编辑了一下,但没有奏效。 请给我一个完整代码的解决方案。我是Java和Android的新手。
我的完整代码:
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
WebView webView;
String url="http://example.com";
TextView textView;
//to hide progressbar after loading part 1
LinearLayout liProgressContainer;
private String currentUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webView);
textView = (TextView) findViewById(R.id.tvLoadingPercentage);
//to hide progressbar after loading part 2
liProgressContainer = (LinearLayout) findViewById(R.id.liProgressContainer);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
textView.setText(progress + " %");
}
});
webView.setWebViewClient(new MyWebViewClient());
WebSettings browserSetting = webView.getSettings();
browserSetting.setJavaScriptEnabled(true);
webView.loadUrl(url);
}
//back button function
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private class MyWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
liProgressContainer.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
//return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
liProgressContainer.setVisibility(View.GONE);
//hide header part
}
}
}
答案 0 :(得分:0)
您需要在MyWebViewClient类中配置shouldOverrideUrlLoading方法,以便仅在符合所需URL的URL时加载该URL。在MyWebViewClient类中添加一个字段以存储URL并添加单个arg构造函数。
private String desiredUrl;
public MyWebViewClient(String url) {
this.desiredUrl = url;
}
在您的shouldOverrideUrlLoading方法中,检查提供的URL是否等于您的URL实例变量。
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (desiredUrl.equals(url))
view.loadUrl(url);
return true;
}
设置Web视图客户端时,请传递您的URL参数,例如
webView.setWebViewClient(new MyWebViewClient(url));