I am getting the following error when I try to find a RecycleView
by id.
Error:- Type inference failed: Not enough information to infer parameter T
Code:
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 } }
New in Android Studio 3.6, view binding gives you the ability to replace findViewById with generated binding objects to simplify code, remove bugs, and avoid all the boilerplate of findViewById .
Kotlin Android Extensions is a great way to avoid writing findViewById in the activity or fragment. Simply, add the kotlin-android-extensions plugin to the module level build. gradle file.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
Try something like:
val recyclerView = findViewById<RecyclerView>(R.id.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 Extensions:
gradle.build
add apply plugin: 'kotlin-android-extensions'
import kotlinx.android.synthetic.main.<layout>.*
where <layout>
is the filename of your layout.recycler_view
directly in your code.How does it work? The first time that you call recycler_view
, a call to findViewById
is done and cached.
You're on API level 26, where the return type of findViewById
is now a generic T
instead of View
and can therefore be inferred. You can see the relevant changelog here.
So you should be able to do this:
val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)
Or this:
val recycler_view: RecyclerView = findViewById(R.id.recycler_view)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With