我正在尝试使用 Kotlin 在我的 Android 应用程序中复制以下 ListView: https ://github.com/bidrohi/KotlinListView。
不幸的是,我遇到了一个我无法解决的错误。这是我的代码:
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listView = findViewById(R.id.list) as ListView
listView.adapter = ListExampleAdapter(this)
}
private class ListExampleAdapter(context: Context) : BaseAdapter() {
internal var sList = arrayOf("Eins", "Zwei", "Drei")
private val mInflator: LayoutInflater
init {
this.mInflator = LayoutInflater.from(context)
}
override fun getCount(): Int {
return sList.size
}
override fun getItem(position: Int): Any {
return sList[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
val view: View?
val vh: ListRowHolder
if(convertView == null) {
view = this.mInflator.inflate(R.layout.list_row, parent, false)
vh = ListRowHolder(view)
view.tag = vh
} else {
view = convertView
vh = view.tag as ListRowHolder
}
vh.label.text = sList[position]
return view
}
}
private class ListRowHolder(row: View?) {
public val label: TextView
init {
this.label = row?.findViewById(R.id.label) as TextView
}
}
}
布局与此处完全相同: https ://github.com/bidrohi/KotlinListView/tree/master/app/src/main/res/layout
我收到的完整错误消息是: Error:(92, 31) Type inference failed: Not enough information to infer parameter T in fun findViewById(p0: Int): T!请明确指定。
我会很感激我能得到的任何帮助。
原文由 Timo Güntner 发布,翻译遵循 CC BY-SA 4.0 许可协议
您必须使用 API 级别 26(或更高)。这个版本改变了
View.findViewById()
的签名 - 见这里 https://developer.android.com/about/versions/oreo/android-8.0-changes#fvbi-signature因此,在您的情况下,
findViewById
的结果不明确,您需要提供类型:1/ 改变
val listView = findViewById(R.id.list) as ListView
到val listView = findViewById<ListView>(R.id.list)
2/ 改变
this.label = row?.findViewById(R.id.label) as TextView
到this.label = row?.findViewById<TextView>(R.id.label) as TextView
请注意,在 2/ 中,仅需要强制转换,因为
row
可以为空。如果label
也可以为空,或者如果您使row
不可为空,则不需要。