我正在嘗試實作 RecyclerView,并按照本教程進行操作: https ://developer.android.com/codelabs/basic-android-kotlin-training-recyclerview-scrollable-list#4
但我試圖將它實作為一個片段而不是主要活動,它最終無法正常作業,所以我開始關注本教程:https ://www.youtube.com/watch?v=__gxd4IKVvk
在大約 24 分鐘時,我們將代碼寫入片段的 .kt 檔案,而他正在使用現已棄用的方法 (onActivityCreated),因此我將代碼放入 onCreateView 中。他可以通過將 xml 檔案中的 id 寫入 var 來訪問它,但這對我不起作用,所以我在將布局膨脹到 val“視圖”中之后訪問了它。然后他訪問了 RecyclerView 的一些屬性(.layoutManager、.itemAnimator、.adapter),但 IDE 說這些都是未決議的參考。我在網上找到的所有內容都表明它應該可以作業,或者我應該使用“.setLayoutManager”和“.setAdapter”,但它們會給出相同的錯誤。我不明白我錯過了什么。
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_exercises, container, false)
val recyclerItems = view.findViewById<RecyclerView>(R.id.exercise_recycler_view)
.hasFixedSize()
recyclerItems.layoutManager = LinearLayoutManager(context)
recyclerItems.itemAnimator = DefaultItemAnimator()
recyclerItems.adapter = ExerciseItemAdapter(viewModel)
return view
}
這是.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
tools:context=".fragments.ExercisesFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@ id/exercise_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layoutManager="LinearLayoutManager" />
</LinearLayout>
uj5u.com熱心網友回復:
我瀏覽了您提供的視頻。
視頻中的人能夠RecyclerView直接訪問,因為他正在使用 kotlin 合成插件:
apply plugin: 'kotlin-android-extensions'
注意:已棄用,您使用的是正確的。或者您可以使用更新的 ViewBinding。
為什么那些未解決的參考?
因為
val recyclerItems = view.findViewById<RecyclerView>(R.id.exercise_recycler_view)
.hasFixedSize()
recyclerItems變成Boolean型別 not RecyclerView。
所以這樣做:
val recyclerItems = view.findViewById<RecyclerView>(R.id.exercise_recycler_view)
recyclerItems.hasFixedSize()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471137.html
