i try to implement recyclerView inside a fragment. When i try to open my app it crashes. i have a BottomNavigationMenu and i want to implement recyclerView inside one of the fragments. here is my code:
HomeFragment.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_home.*
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter:
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>? = null
class HomeFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
layoutManager = LinearLayoutManager(context)
recycler.layoutManager = layoutManager
adapter = RecyclerAdapter()
recycler.adapter = adapter
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
HomeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
how i can implement it correctly
CodePudding user response:
Move your calls to your RecyclerView
from onCreate
to onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
layoutManager = LinearLayoutManager(context)
recycler.layoutManager = layoutManager
adapter = RecyclerAdapter()
recycler.adapter = adapter
}