首页 > 解决方案 > 另一个片段中的 Recyclerview 绑定

问题描述

在房间的帮助下,我正在测试一个简单的应用程序来保存单词。我有 2 个布局片段 - home(main) 和 myword(second)。我正在尝试将以下代码放入 myword 片段中以初始化 recyclerview,但出现未解决的错误。我错了什么?

frag_mywords.xml

    <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/words_dail"
    android:layout_width="0dp"
    android:layout_height="0dp"
    tools:listitem="@layout/recykel_list"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

TakerFragment.kt

class TakerFragment : Fragment() {

private lateinit var takerViewModel: TakerViewModel
private var _binding: FragMywordsBinding? = null

private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    takerViewModel =
        ViewModelProvider(this).get(TakerViewModel::class.java)

    _binding = FragMywordsBinding.inflate(inflater, container, false)
    val root: View = binding.root

    val recyclerView = findViewById<RecyclerView>(R.id.words_dail)
    val adapter = WordListAdapter(this)
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(this)

    return root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
   }
}

我如何正确解决这条线?

val recyclerView = findViewById<RecyclerView>(R.id.words_dail)
    val adapter = WordListAdapter(this)
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(this)

标签: kotlinandroid-fragmentsdata-binding

解决方案


这里有多个问题:

首先更改val recyclerView = findViewById<RecyclerView>(R.id.words_dail)val recyclerView = words_dail

然后,您的 WorldListAdapter 的上下文是错误的,应该是val adapter = WordListAdapter(requireContext())而不是this

第三,您可以在其中设置layoutManager xml

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/words_dail"
android:layout_width="0dp"
android:layout_height="0dp"
tools:listitem="@layout/recykel_list"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" <--
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

使用数据绑定,您还可以在 xml 中设置适配器,但我不知道您是否在适配器中使用数据绑定。


推荐阅读