如何使用 kotlin 在 Android Studio 上正确设置 SwipeRefreshLayout?

How do I properly set SwipeRefreshLayout on Android Studio with kotlin?

我正在尝试在我的项目中使用 SwipeRefreshLayout,但是出了点问题……我不知道是什么! 下面我展示了 kotlin 代码,XML 和我得到的 error

NOTE, it's a FRAGMENT

科特林代码:

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)

OnCreate 在您调用滑动刷新时 onCreateView.your 视图尚未出现之前调用。而是在调用此方法之前进行检查,即 if(activity != null) 。并在 fragment 的 onCreateView 中,为 fragment 提供视图。然后调用这个方法

    override fun onCreateView(inflater: LayoutInflater, 
                            container: ViewGroup?, 
                            savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_dog_details, container, false)
  }

我发现错误: 由于它是一个片段,我只能在 onCreateView 膨胀片段后才能访问 SwipeRefreshLayout。

所以,我在里面设置了监听器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)
        }

    }