kotlin - 另一个片段中的 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)
解决方案
这里有多个问题:
首先更改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 中设置适配器,但我不知道您是否在适配器中使用数据绑定。
推荐阅读
- json - 如何从 JSON 响应中定义此变量?
- reactjs - 如何在单个应用程序池上托管两个反应 js 应用程序?
- read-the-docs - 可以在没有链接存储库的情况下将 Sphinx 源文件推送到 ReadTheDocs 吗?
- c# - 如何更改 DataTable C# 中的列格式
- asp.net-core - ASP.NET Core 中的 Bootstrap 和 bundle 问题
- javascript - 如何在 G Suite Add-on 的服务器和客户端组件中重用单个 JavaScript?
- flutter - 如何在 Flutter 中使用 SharedPreferences 保存模型和 modelDetail
- excel - VBA 上的运行时错误“13”-我该如何解决?
- r - 如何制作多面华夫饼图,从左上角填充每个箱子
- amazon-web-services - AWS DynamoDB 插入多个属性