No more Casting of Android Views in 3 Lines of Code

Edit: I wrote this post a while ago and since then the clever trick described here has been incorporated into Android framework itself. Therefore, you probably already have access to this functionality and use it in your projects. Nevertheless, I’ll leave this post up for historical reference.

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

TextView textView = (TextView) findViewById(R.id.some_text_view);
ImageView imageView = (ImageView) findViewById(R.id.some_image_view);

// 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(R.id.some_text_view);
ImageView imageView = findViewById(R.id.some_image_view);

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 premium

Android Development Courses

One comment on "No more Casting of Android Views in 3 Lines of Code"

Leave a Comment