Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this type casting?

I am using an intent to start another activity, and making my intent carry some data as an extra to the newly created activity. I am following a tutorial to do that.

This data is actually read from a text field in the first activity in the hierarchy, and carried to the other activity as an extra. so my code will be like:

//Make the intent   

Intent intent = new Intent(this, SecondActivity.class);

/* Find the text field (view) which contains the data, and save it into a newly created text field (view of the same type)*/

EditText editText = (EditText) findViewById(R.id.iden1); //******************************

//Read that view's string data into a string called message

String message= editmessage.getText().toString();

//copy this message into the extra named extra_name, of intent.

intent.putExtra(extra_name, message);

My question is from this statement:

EditText editText = (EditText) findViewById(R.id.iden1);

My question is explicit casting i.e. (EditText). Why are we casting the EditText view (which was defined in layout.xml and was identified by android:id="@+id/iden1") returned by findViewById()to an EditText view again. The type of the view editText here and the one created in layout.xml is the same. So what is the point of this type-casting?

like image 599
user2882662 Avatar asked Jun 26 '26 12:06

user2882662


1 Answers

The point is that findViewById(int id) returns a generic View object. This method doesn't parse your xml in order to understand what kind of type is your view. It just makes a new View object from the relationship put in place by your R.java file, built up by your IDE (Eclipse, I suppose).

You need to cast the result of findViewById(int id) because you're not casting an EditText object, your casting a View, of which EditText is only a specification.

like image 96
Gian Segato Avatar answered Jun 28 '26 03:06

Gian Segato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!