Home > front end >  how to use viewbinding in listview?
how to use viewbinding in listview?

Time:04-13

I'm a newbie.I find the listview doesn't show up if i use viewbinding to control the listview.the code is

class MainActivity : AppCompatActivity() {
private val data = listOf("Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val listviewdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
    binding.listview1.adapter = listviewdapter
    
    }
}

and the xml is simple

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ListView
    android:id="@ id/listview1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

but if i use findViewById the listview will show up, why?

class MainActivity : AppCompatActivity() {
private val data = listOf("Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val listviewdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
    val listview1 = findViewById<ListView>(R.id.listview1)
    listview1.adapter=listviewdapter
    }
}

CodePudding user response:

Because list items aren't inflated when the list is created. The binding won't work for the listview at all. It will only work for the main activity. And in fact it couldn't work for the listview- you're going to have multiple of each id, 1 for each on screen element (plus a few possibly). If you want to use viewbinding inside the list view, the binding would have to be in the adapter.

Also, you probably shouldn't be using ListView anymore. Everything moved to RecyclerView about 8 years ago now.

CodePudding user response:

Do like this...

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
 
    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ListView
            android:id="@ id/listview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</layout>

and then you can access your view in code file

binding.listview1
  • Related