我正在尝试使用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
我得到的完整错误消息是: 错误:(92,31)类型推断失败:没有足够的信息来有趣地推断参数T findViewById(p0:Int):T!请明确指定。
我将不胜感激。
this.label = ... as TextView
为this.label = row?.findViewById<TextView>
并这样做val listView = ...
吗?请让我知道这是否可行,以便在这种情况下可以做出正确的回答。