0
findViewById?android help
TextView text1= (TextView) findViewById(R.id.text1); Spinner spinner1= (Spinner)findViewById(R.id.spinner1); what does findViewById(R.id.text1); mean?why is the purpose of using this? does the id refer to the id here? android:id="@+id/text1
11 Answers
+ 12
It means, there must be a TextView element in XML file with id text1 and it's referring to that particular TextView. We have to use id to distinguish between multiple elements.
Suppose you have created an element in layout file, and you need to work on it in another file. You have to get that element using it's id.
This is how we create id in XML layout file:
<TextView
android:id = "@+id/text1"
... other stuffs... />
Same thing is applicable for Spinner as well.
Edit: findViewById method's return type is View (Which is parent class of TextView). That's why it needs to be casted into TextView.
+ 10
Yes :)
+ 10
EditText, TextView, Spinner, Button (and many more) these are called widgets. If I say that they are "in View class", that would not be fully correct. Each widget is in its own class. But their parent/super class is View. So we can say these widgets are siblings 👬👭
And findViewById returns an object of View class, this is how the method was written (and this is a benefit of Inheritance and Polymorphism that one single method can return many type of objects if they share common Parent class).
Since the returned object is View(parent) 👨 and compiler doesn't know which child this is, we have to let it know by casting into appropriate child class 👧
+ 6
Buttons also require to cast the View object (returned by findViewById) into Button class.
Correct statement:
Button submit = (Button) findViewById(R.id.submit_button);
But this one will show error since we can't save a Parent object using Child reference:
Button submit = findViewById(R.id.submit_button);
+ 1
thankyou
+ 1
👍👍thankyou
0
so it is just looking for a specific element(like a button or text) using id created in this android:id="@+id/text1"?
0
sry.one more question.the reason that we cast them is because they are in view class.am i right?
0
sry last question about this topic.why we do not need to cast button unlike spinner and text