问题描述
我正在尝试使用 Kotlin 在我的 Android 应用程序中复制以下 ListView:https://github.com/bidrohi/KotlinListView.
I'm trying to replicate the following ListView in my Android app using Kotlin: https://github.com/bidrohi/KotlinListView.
很遗憾,我遇到了一个无法自行解决的错误.这是我的代码:
Unfortunately I'm getting an error I'm unable to resolve myself.Here's my code:
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) 类型推断失败:没有足够的信息来推断 fun findViewById(p0: Int) 中的参数 T:T!请明确指定.
The full error message I'm getting is this:Error:(92, 31) Type inference failed: Not enough information to infer parameter T in fun findViewById(p0: Int): T!Please specify it explicitly.
如果我能得到任何帮助,我将不胜感激.
I'd appreciate any help I can get.
推荐答案
您必须使用 API 级别 26(或更高).此版本更改了 View.findViewById()
的签名 - 请参阅此处 https://developer.android.com/about/versions/oreo/android-8.0-changes#fvbi-signature
You must be using API level 26 (or above). This version has changed the signature of View.findViewById()
- see here https://developer.android.com/about/versions/oreo/android-8.0-changes#fvbi-signature
因此,在您的情况下,findViewById
的结果不明确,您需要提供类型:
So in your case, where the result of findViewById
is ambiguous, you need to supply the type:
1/改变
val listView = findViewById(R.id.list) as ListView
to
val listView = findViewById(R.id.list)
2/改变
this.label = row?.findViewById(R.id.label) as TextView
to
this.label = row?.findViewById(R.id.label) as TextView
请注意,在 2/中只需要强制转换,因为 row
可以为空.如果 label
也可以为空,或者如果您使 row
不可为空,则不需要.
Note that in 2/ the cast is only required because row
is nullable. If label
was nullable too, or if you made row
not nullable, it wouldn't be required.
这篇关于“没有足够的信息来推断参数 T"使用 Kotlin 和 Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!