Search code examples
androidfindviewbyid

Cast result findViewById android method


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

Solution

  • 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.