在空间的帮助下,我正在测试一个简单的应用程序来保存文字。我有两个布局片段-主页(主)和我的单词(第二)。我正在尝试将下面的代码放在myword片段中,以初始化回收视图,我得到了未解决的错误。我做错什么了?
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)发布于 2020-10-24 09:03:57
这里有多个问题:
首先用val recyclerView = 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" />使用Databinding,您还可以在xml中设置适配器,但我不知道您是否在适配器中使用了绑定。
https://stackoverflow.com/questions/64511218
复制相似问题