Cast result findViewById android method

喜你入骨 提交于 2019-11-27 14:33:01

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!