Cast result findViewById android method

六月ゝ 毕业季﹏ 提交于 2019-11-26 16:48:27

问题


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) ?

回答1:


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.




回答2:


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);



回答3:


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.




回答4:


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);



回答5:


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



来源:https://stackoverflow.com/questions/22805869/cast-result-findviewbyid-android-method

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