Warrior4EVA
Warrior4EVA

Reputation: 27

why we need to casting views in android?

I'm just was wondering why we are actually casting views when we initialize it by using findViewById() method, I mean what does findViewById() method return back, and why we need to cast the result.

TextView txtview;

txtview = (TextView) findViewById(R.id.textViewID);

Upvotes: 0

Views: 278

Answers (2)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

Note: You are not initializing, you are assigning there from a already created view object with childs

In the past the signature of the method was

public View findViewById(@ResId int id)

The downcast from View to any subtype (TextView, EditText, ImageView, etc) was necessary and old articles still uses this method.

Now days the signature is generic as:

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

Meaning it returns it value cast to T, T is resolved with the left side of the assignment declaration (before the equals) so we can simply do:

TextView t = view.findViewById(R.id.tv_x);

The value of T is TextView from the left side of the assignment.

Also consider the following method signature:

void x(TextView t, ImageView i)

You can infer T while calling this resulting the method being called with a Textview and a ImageView instead of the super class View:

x(view.findViewById(R.id.tv_x), view.findViewById(R.id.iv_x))

While this assignment would need downcasting:

View v = view.findViewById(R.id.tv_x);
//v.text = "x" HERE we don't know the type was not infered to TextView
((TextView) v).text = "x"; //unsafe downcasting necessary

Ps: the inferred type of T is unsafe below View

Upvotes: 2

ruben
ruben

Reputation: 1750

This casting is actually optional. Please check here that this call returns the view or null otherwise

Alternatively if you use view binding you don't even need to use findViewById

Upvotes: 0

Related Questions