强制转换结果findViewById android方法 [英] Cast result findViewById android method
问题描述
为什么我们总是必须强制转换方法findViewById(id)
返回的值?正如我在Google参考中看到的那样,该方法已经返回了一个视图:
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) ?
推荐答案
方法findViewById()
返回实际上用于在XML文件中定义该视图的类的实例.方法签名返回View
以使其通用且可用于所有为View
继承的类.
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不会为您隐式强制转换.
Java won't cast that implicitly for you.
您可以将其保留为:
View image = findViewById(R.id.image);
,但是您将无法使用在ImageView
类上定义的方法等.
but you wouldn't be able to use the methods, etc. defined on ImageView
class.
这篇关于强制转换结果findViewById android方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!