【发布时间】:2020-10-24 07:58:28
【问题描述】:
在房间的帮助下,我正在测试一个简单的应用程序来保存单词。我有 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)
【问题讨论】:
-
你能发布确切的堆栈跟踪吗?
findViewById<RecyclerView>(R.id.recyclerview)可能不正确,因为您的 RecyclerView ID 是words_dail。所以应该是findViewById<RecyclerView> (R.id.words_dail)。但是你不再需要使用findViewById,使用 kotlin syntethics。所以只需要写val recyclerview = words_dail然后导入syntethics -
是的,我更正了 words_dail。这是堆栈跟踪pastebin.com/hL0nHpUJ
标签: kotlin android-fragments data-binding