When using SwipeRefreshLayout with WebView (as child view), scrolling upwards on a website does not work since the swipe down to refresh action is being triggert instead.
Every solution I have found online does not seem to work for me. I have tried using NestedScrollView, ViewTreeObserver OnScrollChangedListener and CanChildScrollUpCallback. The last solution seems to be the most recommended one so I would prefer a solution using the callback method. Here is how I tried to implement it:
swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));
But I can't get it to work and I don't know why. Any help is appreciated.
Here is the rest of the code that goes along with it:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);
webView = findViewById(R.id.web_view);
swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));
swipeRefreshLayout.setOnRefreshListener(
() -> {
webView.reload();
swipeRefreshLayout.setRefreshing(false);
}
);
webView.setWebViewClient(new WebViewClient());
CookieManager.getInstance().setAcceptCookie(true);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
String url = "https://WEBSITE";
webView.loadUrl(url);
}
}