无法“findViewById"在科特林.获取错误“类型推断失败" [英] Not able to "findViewById" in Kotlin. Getting error "Type inference failed"
本文介绍了无法“findViewById"在科特林.获取错误“类型推断失败"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试通过 id 查找 RecycleView
时出现以下错误.
I am getting the following error when I try to find a RecycleView
by id.
错误:-类型推断失败:没有足够的信息来推断参数 T
Error:- Type inference failed: Not enough information to infer parameter T
代码:
class FirstRecycleViewExample : AppCompatActivity() {
val data = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first_recycleview)
val recycler_view = findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR
data.add("First Data")
data.add("Second Data")
data.add("Third Data")
data.add("Forth Data")
data.add("Fifth Data")
//creating our adapter
val adapter = CustomRecycleAdapter(data)
//now adding the adapter to recyclerview
recycler_view.adapter = adapter
}
}
推荐答案
尝试类似:
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
您也可以为此使用 Kotlin Android 扩展
.在此处查看文档.
有了它,您可以直接在代码中调用 recycler_view
.
You can use Kotlin Android Extensions
too for that. Check the doc here.
With it, you can call recycler_view
directly in your code.
Kotlin Android 扩展:
- 在你的应用
gradle.build
中添加apply plugin: 'kotlin-android-extensions'
- 在您的课程中为
import kotlinx.android.synthetic.main.
添加 import,其中.*
是您的布局的文件名. - 就是这样,您可以直接在代码中调用
recycler_view
.
- In your app
gradle.build
addapply plugin: 'kotlin-android-extensions'
- In your class add import for
import kotlinx.android.synthetic.main.<layout>.*
where<layout>
is the filename of your layout. - That's it, you can call
recycler_view
directly in your code.
它是如何工作的?第一次调用 recycler_view
时,会调用 findViewById
并缓存.
How does it work? The first time that you call recycler_view
, a call to findViewById
is done and cached.
这篇关于无法“findViewById"在科特林.获取错误“类型推断失败"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文