I have a simple project, and I want to use bottom sheet for list items in fragment, every things looks good, but after build the project, app crash like that,
a null object reference for row_list.setOnLongClickListener
I do not know where is the problem and how I will fix this problem, maybe my approach is not correct, any idea will be appreciated.
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)
}
}
CodePudding user response:
During onCreate()
views are not initialized completely or are in ambiguous state.
Simple answer is to move the view logic to 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
}
}