You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中实现ListView展示用户输入列表需补充的步骤

实现Android ListView添加并展示用户输入名称的完整步骤

你当前的代码还有几处关键缺失,按以下步骤修改即可正常运行:

1. 修正输入文本的获取源

你现在错误地获取了按钮的文本,应该获取EditText的输入内容。首先在代码中获取EditText实例:

// 获取输入框实例(替换成你布局中EditText的id)
val playerInput = findViewById<EditText>(R.id.et_player_input)

然后修改按钮点击事件的逻辑,添加输入框的文本到列表,并清空输入框:

AddPlayer.setOnClickListener {
    val playerName = playerInput.text.toString().trim()
    if (playerName.isNotEmpty()) { // 避免添加空字符串
        AllPlayersHidden.add(playerName)
        playerInput.text.clear() // 清空输入框
        // 后续还要通知Adapter更新,见步骤4
    }
}

2. 让Adapter关联数据列表

当前Adapter完全没有和你的AllPlayersHidden列表关联,需要修改Adapter的构造函数,让它持有数据列表:

private class MyCustomAdapter(
    private val mContext: Context,
    private val playerList: MutableList<String> // 添加数据列表参数
) : BaseAdapter() {

    // 负责返回列表行数,改为返回数据列表的大小
    override fun getCount(): Int {
        return playerList.size
    }

    // 返回对应位置的数据项
    override fun getItem(position: Int): Any {
        return playerList[position]
    }

    // 渲染每一行的内容,改为显示对应位置的玩家名称
    override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
        // 优化:复用convertView提升性能
        val textView = if (convertView == null) {
            TextView(mContext).apply {
                // 可以设置一些样式,比如内边距、文字大小
                setPadding(16, 16, 16, 16)
                textSize = 18f
            }
        } else {
            convertView as TextView
        }
        textView.text = playerList[position]
        return textView
    }

    // 其他方法保持不变
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }
}

3. 初始化Adapter时传入数据列表

修改ListView的Adapter初始化代码,把AllPlayersHidden列表传进去,同时保存Adapter实例以便后续更新:

// 保存Adapter实例
val playerAdapter = MyCustomAdapter(this, AllPlayersHidden)
val AllPlayers = findViewById<ListView>(R.id.AllPlayers)
AllPlayers.adapter = playerAdapter

4. 添加数据后通知Adapter更新

在按钮点击事件中,添加完数据后调用Adapter的notifyDataSetChanged()方法,让ListView刷新显示:

AddPlayer.setOnClickListener {
    val playerName = playerInput.text.toString().trim()
    if (playerName.isNotEmpty()) {
        AllPlayersHidden.add(playerName)
        playerInput.text.clear()
        playerAdapter.notifyDataSetChanged() // 通知Adapter数据更新
    }
}

完成以上修改后,你的应用就能实现用户输入名称、添加到列表并实时在ListView中展示的功能了。

内容的提问来源于stack exchange,提问作者enor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:09:22