问题
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.
NOTE, it's a FRAGMENT
KOTLIN CODE:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
swipeRefresh.setOnRefreshListener {
refreshAction() // refresh your list contents somehow
swiperefresh_saloes.isRefreshing = false
}
}
XML CODE
<?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>
but I'm getting the following error:
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)
回答1:
I found the error: Since it's a fragment, I can only access the SwipeRefreshLayout after onCreateView inflates the fragment.
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)
}
}
回答2:
OnCreate calls before onCreateView.your view is yet not present when you are calling swipe refresh . Instead put a check before calling this method i.e if(activity != null) . And in onCreateView of fragment , provide the view to fragment . Then call this method
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_dog_details, container, false)
}
来源:https://stackoverflow.com/questions/55973970/how-do-i-properly-set-swiperefreshlayout-on-android-studio-with-kotlin