Я пытаюсь добавить RecyclerView к фрагменту, но у меня возникла проблема.
Мой код в настоящее время выдает «java.lang.IllegalStateException: это не должно быть нулевым» в строке 44моего кода:
layoutManager = LinearLayoutManager(this.context)
Как правильно ссылаться на мой RecyclerView, чтобы я мог инициализировать его с данными?
package com.example.subshop
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_receipt.*
import kotlinx.android.synthetic.main.fragment_receipt.view.*
import kotlinx.android.synthetic.main.fragment_receipt.view.toppingRecyclerView
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class ReceiptFragment : Fragment() {
private lateinit var toppingAdapter: ToppingAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initRecyclerView()
addToppingList()
}
private fun initRecyclerView() {
toppingAdapter = ToppingAdapter()
toppingRecyclerView.apply {
layoutManager = LinearLayoutManager(this.context)
adapter = toppingAdapter
}
}
private fun addToppingList() {
toppingAdapter.submitList(ReceiptFragmentArgs.fromBundle(arguments!!).sandwich.toppings)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_receipt, container, false)
val sandwich = ReceiptFragmentArgs.fromBundle(arguments!!).sandwich
view.sandwichAndBreadText.text = "${sandwich.name} on ${sandwich.breadName}"
view.totalText.text = "Total: \$${sandwich.basePrice + sandwich.toppingPrice}"
view.doneButton.setOnClickListener {
findNavController().navigate(ReceiptFragmentDirections.actionReceiptFragmentToWelcomeFragment())
}
return view
}
}