By accident I found that there is a support library for WebView that is part of AndroidX: androidx.webkit:webkit:1.0.0
However I could not find any sample code on how to use it and the JavaDoc is not much of a help either: https://developer.android.com/reference/androidx/webkit/package-summary
Is this supposed to be used by developers or is it an internal library?
This library is an androidx
abstraction for WebKit
(as it relies on an update-able APK).
WebViewCompat.java itself tells "do not instantiate this" (and also the XML tag is unknown, so one has to use android.webkit.WebView
); but class WebViewCompat has several public static
methods, which are accessible; Also WebViewFeature seems relevant (the IDE complained).
When using these imports:
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.webkit.SafeBrowsingResponseCompat;
import androidx.webkit.WebResourceErrorCompat;
import androidx.webkit.WebViewClientCompat;
import androidx.webkit.WebViewFeature;
import androidx.webkit.WebViewCompat;
using WebViewClientCompat works about like this:
private WebView mWebView;
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.mWebView.setWebViewClient(new WebViewClientCompat(){
@Override
public void onPageCommitVisible(@NonNull WebView view, @NonNull String url) {
super.onPageCommitVisible(view, url);
}
@Override
public void onReceivedError(@NonNull WebView view, @NonNull WebResourceRequest request, @NonNull WebResourceErrorCompat error) {
super.onReceivedError(view, request, error);
}
@Override
public void onReceivedHttpError(@NonNull WebView view, @NonNull WebResourceRequest request, @NonNull WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onSafeBrowsingHit(@NonNull WebView view, @NonNull WebResourceRequest request, int threatType, @NonNull SafeBrowsingResponseCompat callback) {
super.onSafeBrowsingHit(view, request, threatType, callback);
}
@Override
public boolean shouldOverrideUrlLoading(@NonNull WebView view, @NonNull WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});
}
implementing interface
WebViewCompat.VisualStateCallback works alike this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && WebViewFeature.isFeatureSupported(WebViewFeature.VISUAL_STATE_CALLBACK)) {
final int mVisualStateCallbackId = 500;
WebViewCompat.postVisualStateCallback(mWebView, mVisualStateCallbackId, new WebViewCompat.VisualStateCallback() {
@Override
public void onComplete(long requestId) {
if (requestId == mVisualStateCallbackId) {
mWebView.setVisibility(View.VISIBLE);
}
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With