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 :
/home/onkar/AndroidStudioProjects/MyApplication2/app/src/main/java/io/github/omkar76/myapplication/MainActivity.java:16: error: cannot find symbol Log.d("EDITTEXT", findViewById<EditText>(R.id.first_name).getText()); ^ symbol: variable findViewById location: class MainActivity
Why isn’t this working? Why is method not found? I even checked source of AppCompatActivity
and it does contain required method:
@Override public <T extends View> T findViewById(@IdRes int id) { return getDelegate().findViewById(id); }
My Java code is :
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("EDITTEXT", findViewById<EditText>(R.id.first_name).getText()); } }
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
Edittext x = view.findViewById(R.id.abc)
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