android-fragments 回收器视图未显示片段中的结果

jrcvhitl  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(207)

我尝试在我的一些片段中实现回收器视图,并且我尝试在第一个片段中这样做。在编译时,IDE中没有显示任何问题,但在运行时,我在控制台上收到以下消息:E/RecyclerView: No layout manager attached; skipping layout。此外,数据未显示在我的应用程序中。
这是我的片段:

var sandwiches = listOf<Sandwich>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = DataBindingUtil.inflate<FragmentSandwichesBinding>(
            inflater,
            R.layout.fragment_sandwiches, container, false
        )

        val application = requireNotNull(this.activity).application
        val dataSource = NbaCafeDB.getInstance(application).sandwichDao
        val viewModelFactory = SandwichViewModelFactory(dataSource, application)

        val sandwichViewModel =
            ViewModelProvider(this, viewModelFactory).get(SandwichViewModel::class.java)

        sandwiches = sandwichViewModel.getAll()

        val adapter = SandwichAdapter(sandwiches)
        binding.sandwichRecycler.adapter = adapter

        binding.setLifecycleOwner(this)

        return binding.root
    }

}

这是我的适配器:

class SandwichAdapter (val sandwich: List<Sandwich>) : RecyclerView.Adapter<SandwichAdapter.SandwichHolder>() {

    override fun getItemCount() = sandwich.size

    class SandwichHolder(val view: View) : RecyclerView.ViewHolder(view) {
        fun bind(sandwich: Sandwich) {
            view.findViewById<TextView>(R.id.sandwichNom).text = sandwich.nomSandwich
            view.findViewById<TextView>(R.id.sandwichDesc).text = sandwich.descSandwich
            view.findViewById<TextView>(R.id.sandwichPreu).text = (sandwich.preuSandwich.toString()+" €")
        }

        companion object {
            fun from(parent: ViewGroup): SandwichHolder {
                val layoutInflater = LayoutInflater.from(parent.context)
                val view = layoutInflater
                    .inflate(R.layout.sandwich_cell_layout, parent, false)

                return SandwichHolder(view)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SandwichHolder {
        return SandwichHolder.from(parent)
    }

    override fun onBindViewHolder(holder: SandwichHolder, position: Int) {
        holder.bind(sandwich[position])
    }

}

另外,我正在从一个房间数据库中检索数据,并使用viewModel和viewModelFactory,以防发生任何变化。谢谢!

watbbzwu

watbbzwu1#

您不需要呼叫RecyclerView.setLayoutManager(layoutManager)
只需在xml中将app:layoutManager添加到RecyclerView即可。
LinearLayoutManager的默认方向是VERTICAL,但如果要将方向更改为HORIZONTAL,只需添加android:orientation="horizontal"即可。

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical|horizontal"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

相关问题