我正在构建一个应用程序,允许用户在Web视图中单击指向pdf文档的链接并在视图中显示它.我使用谷歌文档查看PDF文件工作,但我的问题是,我只希望该方法适用于PDF链接而不是每个链接,继承我的代码:
public class HelloWebViewActivity extends Activity
{
WebView mWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://nuigalway.blackboard.com/webapps/login/");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
String googleDocs = "https://docs.google.com/viewer?url=";
mWebView.loadUrl(googleDocs + url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
我认为错误在shouldOverrideUrlLoading方法中.是否有任何方法只允许我在webview中单击文件本身时打开pdf网址?
解决方法:
您的shouldOverrideUrlLoading逻辑不正确. url参数是被点击的网址.所以你想拦截任何pdf链接,但让webview正常处理所有其他网址.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.endsWith(".pdf"))
{
// Load "url" in google docs
}
else
{
// Load all other urls normally.
view.loadUrl(url);
}
return true;
}
标签:android,pdf,google-docs,webview
来源: https://codeday.me/bug/20190726/1539813.html