无法"findViewById";在科特林.得到错误“类型推断失败". [英] Not able to "findViewById" in Kotlin. Getting error "Type inference failed"

查看:96
本文介绍了无法"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 Extensions.在此处上查看文档.
有了它,您可以直接在代码中调用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.<layout>.*添加导入,其中<layout>是布局的文件名.
  • 就是这样,您可以直接在代码中调用recycler_view.
  • In your app gradle.build add apply 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆