问题描述
我正在尝试在项目中使用SwipeRefreshLayout,但是出了点问题...我不知道该怎么办!下面我显示kotlin
代码,XML
和我得到的error
.
I'm trying to use a SwipeRefreshLayout on my project, but there's something wrong... and I don't know what!Below I show the kotlin
code, XML
and the error
I'm getting.
科林码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
swipeRefresh.setOnRefreshListener {
refreshAction() // refresh your list contents somehow
swiperefresh_saloes.isRefreshing = false
}
}
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".Activities.Fragments.SaloesFragment">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefresh"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerViewSaloes"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
但出现以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法"void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout $ OnRefreshListener)" 在com.zowye.b2b.Activities.Fragments.SaloesFragment.onCreate(SaloesFragment.kt:69)
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout$OnRefreshListener)' on a null object reference at com.zowye.b2b.Activities.Fragments.SaloesFragment.onCreate(SaloesFragment.kt:69)
推荐答案
我发现了错误:由于是片段,因此只能在onCreateView扩展片段之后才能访问SwipeRefreshLayout.
I found the error:Since it's a fragment, I can only access the SwipeRefreshLayout after onCreateView inflates the fragment.
因此,我将侦听器设置为onViewCreated
So, I setted the listener inside onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
swipeRefresh.setOnRefreshListener {
refreshAction() // refresh your list contents somehow
swipeRefresh.isRefreshing = false // reset the SwipeRefreshLayout (stop the loading spinner)
}
}
这篇关于如何使用Kotlin在Android Studio上正确设置SwipeRefreshLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!