我们如何在 android 的 RecyclerView 片段中使用 bottomSheet?

How we can use bottomSheet in fragment for RecyclerView in android?

我有一个简单的项目,我想将底部 sheet 用于片段中的列表项,一切看起来都不错,但是在构建项目之后,应用程序崩溃了,

a null object reference for row_list.setOnLongClickListener

我不知道问题出在哪里,我将如何解决这个问题,也许我的方法不正确,任何想法将不胜感激。

fragment_list:

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:fitsSystemWindows="true"
        tools:context=".view.ListFragment">


    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/row_list"
            app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="60dp">
    </androidx.recyclerview.widget.RecyclerView>

   </FrameLayout>

ListFragment:

class ListFragment : Fragment() {

    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        row_list.setOnLongClickListener {

            val bottomSheetFragment: BottomSheetDialogFragment = RowItemMenuFragment()
            bottomSheetFragment.show(requireFragmentManager(), bottomSheetFragment.tag)

            true
        }}
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.fragment_list, container, false)

        return view

    }}}

RowItemMenuFragment:

class RowItemMenuFragment() : BottomSheetDialogFragment()  {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_row_item_menu, container, false)

    }

    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.BottomSheetDialogTheme)

    }

  }

onCreate() 期间,视图未完全初始化或处于不明确状态。

简单的答案是将视图逻辑移动到 onViewCreated()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        row_list.setOnLongClickListener {

            val bottomSheetFragment: BottomSheetDialogFragment = RowItemMenuFragment()
            bottomSheetFragment.show(requireFragmentManager(), bottomSheetFragment.tag)

            true
        }
}