Question

Why do we always have to cast the value returned by the method findViewById(id) ? The method already returns a view, as I've seen in google reference :

http://developer.android.com/reference/android/view/View.html#findViewById(int)

Then is it possible to cast to another thing apart form a view ? For example, do this :

ImageView image = (ImageView) findViewById(R.id.image) ?
Was it helpful?

Solution 2

The method findViewById() returns an instance of the class that is actually used to define that view in your XML file. The method signature returns a View to make it generic and usable for all classes that inherit for View.

You need to cast the returned value to the class that your variable is defined when you use it like:

ImageView image = (ImageView) findViewById(R.id.image);

Java won't cast that implicitly for you.

You could leave it as:

View image = findViewById(R.id.image);

but you wouldn't be able to use the methods, etc. defined on ImageView class.

OTHER TIPS

I always define a method which does the casting for me in my base activity:

@SuppressWarnings("unchecked")
public <T extends View> T $(int id) {
    return (T) findViewById(id);
}

This means instead of:

Button btn = (Button)findViewById(R.id.btn);

You can do:

Button btn = $(R.id.btn);

View is the common superclass of other view classes such as ImageView. In object-oriented polymorphism, you can substitute a specific instance e.g. ImageView with the superclass. This is useful in generic APIs such as findViewById() return value.

Downcasting to a more specific type in Java requires an explicit cast.

We cast it to a particular view like ImageView or TextView when we need to use certain properties pertaining to those type of views. For example, you will use

ImageView image = (ImageView) findViewById(R.id.image); 

and then use image to set some properties of an ImageView explicitly. For instance,

image.setImageBitmap();
image.setImageAlpha();

and the like. When you don't need to use any specific properties for the view, then no need of casting. For instance, in Android any view can be set visible, gone or invisible. In that case there is no need of type casting. Even the following will work.

View image = findViewById(R.id.image);
image.setVisibility(View.VISIBLE);

Yes, findViewById() returns View. You can omit casting if you don't need to use the methods of any direct/indirect subclasses, that extends View, such as ImageView, LinearLayout, TextView etc.

View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.)

And of course you can downcast to any subclass of View

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top