我正试图在Android Studio中创建一个应用程序,用户需要在其中输入将存储在列表中的多个名称我还想用ListView向用户显示该列表。
现在我的方法是有一个EditText容器,用户可以在其中输入文本,然后按下按钮,它就会将其添加到列表中;AllPlayersHidden";。从那里它将更新适配器,然后更新ListView。
以下是主要功能片段:
// List of players that is shown
val AllPlayers = findViewById<ListView>(R.id.AllPlayers)
AllPlayers.adapter = MyCustomAdapter(this) //adapter telling listview what to show
// Hidden list
val AllPlayersHidden = mutableListOf<String>()
// Button to input name into list
val AddPlayer = findViewById<Button>(R.id.AddPlayer)
AddPlayer.setOnClickListener {
AllPlayersHidden.add(AddPlayer.getText().toString())
这是完整的适配器:
private class MyCustomAdapter(context: Context): BaseAdapter() {
private val mContext: Context
init {
this.mContext = context
}
//responsible for amount of rows in list
override fun getCount(): Int {
return 5
}
// you can also ignore this
override fun getItemId(position: Int): Long {
return position.toLong()
}
// you can ignore this for now
override fun getItem(position: Int): Any {
return "TEST STRING"
}
// responsioble for rendering out each row
override fun getView(p0: Int, convertView: View?, viewGroup: ViewGroup?): View {
val textView = TextView(mContext)
textView.text =
return textView
}
我还需要做什么,才能让它发挥作用
更好的方法是使用简单的ArrayAdpter并删除CustomAdapter
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, AllPlayersHidden. toTypedArray());