【发布时间】:2021-11-10 21:50:11
【问题描述】:
我正在尝试向 webview 布局添加简单的滑动刷新。我到处搜索并尝试了与我在 GitHub 和 Android 开发人员页面上找到的方法不同的方法,但似乎没有任何效果。当我在代码中没有 OnRefresh 方法的代码加载网页时,它加载得很好。但是一旦我启用该方法,页面就会关闭应用程序。任何建议都会很棒,因为我是 android 新手(1 年经验)并正在努力学习。谢谢
这是我正在使用的代码示例。希望我每次在这里提出问题时都不会发布太多信息,我被告知我发布太多了!
private AboutViewModel AboutViewModel;
SwipeRefreshLayout swipe;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root;
AboutViewModel = new ViewModelProvider(this).get(AboutViewModel.class);
root = inflater.inflate(R.layout.fragment_about, container, false);
WebView webView = root.findViewById(R.id.web_view_about);
webView.loadUrl("https://example.com");
webView.setWebViewClient(new WebViewController());
swipe = (SwipeRefreshLayout) container.findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webView.reload();
}
});
return root;
}
这是布局xml
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/web_view_about"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
【问题讨论】:
-
如果在
webView.reload();之后添加swipe.setRefreshing(false);会发生什么? -
仍然关闭。 Logcat:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void androidx.swiperefreshlayout.widget.SwipeRefreshLayout.setOnRefreshListener(androidx.swiperefreshlayout.widget.SwipeRefreshLayout$OnRefreshListener)”
-
我想它指的是这个? swipe = (SwipeRefreshLayout) container.findViewById(R.id.swipe); swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
-
swipe = (SwipeRefreshLayout) container.findViewById(R.id.swipe); swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()- 不!没关系