No more Casting of Android Views in 3 Lines of Code

By | 2018-04-22T20:30:00+00:00 February 1st, 2017|Android development|1 Comment

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.

Check out my advanced Android development courses on Udemy

Subscribe for new posts!

One Comment

  1. Nebojša Kamber September 15, 2017 at 11:48 am - Reply

    And now, with Android Oreo (API 26), casting nor workaround isn’t needed at all 😉

Leave A Comment