'Want to create a list of view items in android studio
I want to create a list of clickable items as :
val clickableViews: List<View> = listOf(box_one_text, box_two_text, box_three_text, box_four_text, box_five_text, constraint_layout)
where box_xxx_text parameters are view-ids of different items. Does anyone know how to do it?
Solution 1:[1]
Since you have to add predefined elements, it's more convenient to use an array instead of a list.
val array = arrayOf(
"One", "Two", "Three")
The first step to create a ListView is of course defining a ListView in your xml layout file.
<ListView
android:id="@+id/list_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
This should do. The second step is to define an array adapter to insert your array into your listview.
val arrayAdapter: ArrayAdapter<*>
Then you can create a variable for the listview, and add your array into it
var mListView = findViewById<ListView>(R.id.list_view)
arrayAdapter = ArrayAdapter(this,
android.R.layout.layoutfilename, array)
mListView.adapter = arrayAdapter
Job done, hope it helps!
Solution 2:[2]
You could try applying view binding, I'd say that's the most efficient way...
This solution and a couple more variants are described here:
https://github.com/udacity/andfun-kotlin-color-my-views/issues/11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabriele Santoro |
| Solution 2 | Anna Melentyeva |
