I'm trying to implement a RecyclerView, and I followed this tutorial: https://developer.android.com/codelabs/basic-android-kotlin-training-recyclerview-scrollable-list#4
but I am trying to implement it into a fragment instead of the main activity, and it ended up not working, so I started following this tutorial: https://www.youtube.com/watch?v=__gxd4IKVvk
At about 24 min we are writing code into the fragment's .kt file and he is using a now deprecated method (onActivityCreated), so I'm putting the code into onCreateView instead. He is able to access the id from the xml file by just writing it as a var, but this does not work for me, so I've accessed it after inflating the layout into the val "view." He then accesses some properties of the RecyclerView (.layoutManager, .itemAnimator, .adapter), but the IDE is saying that these are all unresolved references. Everything I've found online suggests it should just work or that I should use ".setLayoutManager" and ".setAdapter", but those give the same error. I don't understand what I'm missing.
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
}
Here is the .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>
CodePudding user response:
I went through the videos that you provided.
The guy in the video is able to access the RecyclerView
directly because he's using the plugin for kotlin synthetic:
apply plugin: 'kotlin-android-extensions'
Note: Which is deprecated & what you're using is correct. Or you can go with newer ViewBinding.
Why those unresolved references?
Because of
val recyclerItems = view.findViewById<RecyclerView>(R.id.exercise_recycler_view)
.hasFixedSize()
recyclerItems
becomes the Boolean
type not RecyclerView
.
So do it like this:
val recyclerItems = view.findViewById<RecyclerView>(R.id.exercise_recycler_view)
recyclerItems.hasFixedSize()