Skip to content
Advertisement

findViewById not accepting type argument even with compileSdkVersion 30

I generally use kotlin for android but my college wants me to use Java. So I created a new java project in android studio.

The problem is I don’t want to cast the return value of findViewById() manually. Instead I want to pass EditText as type parameter which the function is not accepting as anticipated. I get the error :

JavaScript

Why isn’t this working? Why is method not found? I even checked source of AppCompatActivity and it does contain required method:

JavaScript

My Java code is :

JavaScript

If I don’t pass type argument EditText, findViewById returns View which then I need to manually cast. According to this post starting with api 26 you don’t need to cast the returned value. I have API 30 SDK. So why this is not working. I am aware of workarounds like assigning return value to an EditText reference but my interest is in knowing why existig approach doesn’t work.

Let me know if any other details are required. Please point out what I am doing wrong. Thanks!

Advertisement

Answer

I think you’re confused with the syntax of java.

Here public <T extends View> T findViewById(@ResId int id) means :

return value cast to T, T is resolved with the left side of the assignment declaration before the equals sign. In the following example

JavaScript

So here T get assigned as Edittext as Edittext is on the left side of the assignment declaration which then returns edittext as a view. Then you can call x to getstring. Hope this makes it clearer

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement