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

Android Studio中Kotlin实现ListView显示ArrayList联系人名称问题

解决方法

要让ListView显示联系人的name属性,有两种简单的实现方式:

方法一:重写Contact类的toString()方法

ArrayAdapter默认会调用数据对象的toString()方法生成列表项的显示文本,直接在Contact类里重写这个方法,让它返回联系人名称即可:

data class Contact(val name: String, /* 可添加其他属性如phone等 */) {
    override fun toString(): String {
        return name
    }
}

修改后你原有的Adapter代码无需改动,ListView会自动显示每个联系人的名字。

方法二:自定义ArrayAdapter控制显示内容

如果不想修改Contact类的toString(),可以自定义Adapter手动设置列表项文本:

1. 创建自定义Adapter类

class ContactAdapter(context: Context, private val contactList: List<Contact>) :
    ArrayAdapter<Contact>(context, android.R.layout.simple_list_item_1, contactList) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        // 复用布局提升性能
        val itemView = convertView ?: LayoutInflater.from(context)
            .inflate(android.R.layout.simple_list_item_1, parent, false)
        
        // 设置TextView显示联系人名称
        val textView = itemView.findViewById<TextView>(android.R.id.text1)
        textView.text = contactList[position].name
        
        return itemView
    }
}

2. 替换原Adapter

在按钮点击事件中使用自定义Adapter:

showAllContactsBtn.setOnClickListener {
    val adapter = ContactAdapter(this, listOfAllNames)
    listNames.adapter = adapter
    
    listNames.setOnItemClickListener { _, _, position, _ ->
        Toast.makeText(this, "Contact picked: ${listOfAllNames[position].name}", Toast.LENGTH_LONG).show()
    }
}

注意:修复拼写错误

你原代码Toast中的listofAllnames是小写开头,和定义的listOfAllNames大小写不一致,会导致编译错误,记得改成一致命名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:10:48