This is the simple answer how to add datas dynamically in listview android kotlin
class MainActivity : AppCompatActivity(){
var listItems = arrayListOf<String>()
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<String>()
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<String>()){
this.itemsList = listItems
notifyDatSetChanged
}
}
//Here I just explained two ways, we can do this many ways.
4 votes
La réponse de Shardul qui a obtenu le plus grand nombre de votes est considérée comme étant de haute qualité et les utilisateurs ont exprimé le souhait qu'elle soit acceptée. Pouvez-vous envisager de l'accepter ?