Casting View Android

View casting boilerplate:

Every Android developer knows (and, probably, hates) this syntax that involves casting:

        TextView textView = (TextView) findViewById(;
        ImageView imageView = (ImageView) findViewById(;

        // same pattern for each subclass of View ...

Ideal state:

How would you react if I told you that with just 3 lines of code, without any libraries you could do it this way:

        TextView textView = findViewById(;
        ImageView imageView = findViewById(; 

Well, you can!

No more Views casting:

The following function relies on Java’s generics automatic type inference in order to eliminate a need for manual casting:

    protected <T extends View> T findViewById(@IdRes int id) {
        return (T) getRootView().findViewById(id);

and it’s just three lines of code (if you count in the line for closing curly bracket)!

So, go ahead and copy-paste this code into base classes of your MVC views, Fragments or Activities (though it is a bit trickier to get the root of Activity view hierarchy), and forget about View casting forever.

Please leave your comments and questions below, and consider subscribing to our newsletter if you liked the post.

This article has 1 comments

Leave a Comment

Your email address will not be published. Required fields are marked *