How do you dynamically add elements to a ListView on Android?

后端 未结 7 2149
情歌与酒
情歌与酒 2020-11-22 08:47

Can anyone explain or suggest a tutorial to dynamically create a ListView in android?

Here are my requirements:

  • I should be able to dynamically add new e
7条回答
  •  借酒劲吻你
    2020-11-22 09:35

            This is the simple answer how to add datas dynamically in listview android kotlin
    
    
    class MainActivity : AppCompatActivity(){
            
                var listItems = arrayListOf()
                val array = arrayOf("a","b","c","d","e")
                var listView: ListView? = null
        
                private lateinit var adapter: listViewAdapter
            
                override fun onCreate(savedInstanceState: Bundle?) {
                    super.onCreate(savedInstanceState)
                    setContentView(R.layout.scrollview_layout)
            
                    listItems.add("a")
                    listItems.add("b")
                    listItems.add("c")
                    listItems.add("d")
                    listItems.add("e")
            
                    //if you want to add array items to a list you can try this for each loop
                    for(items in array)
                        listItems.add(items)
                    
                    //check the result in console
                    Log.e("TAG","listItems array: $listItems")
        
                adapter = ListViewAdapter()
                adapter.updateList(listItems)
                adapter.notifyDataSetChanged()
            
                }
            }
    
    
    //Here is the adapter class
        class ListviewAdapter : BaseAdapter(){
        
        private var itemsList = arrayListOf()
        
        override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
                var view  = container
                val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                if (view == null)
                    view = inflater.inflate(R.layout.list_pc_summary, parent, false)
        
        return view
        }
        
        override fun getItem(position: Int): Any  = itemsList[position]
        
        override fun getItemId(position: Int): Long = position.toLong()
        
        override fun getCount(): Int = itemsList.size
        
        fun updateList(listItems: ArrayList()){
            this.itemsList = listItems
            notifyDatSetChanged
        
        }
       
            }
           
        //Here I just explained two ways, we can do this many ways.
    

提交回复
热议问题