No more Casting of Android Views in 3 Lines of Code

//No more Casting of Android Views in 3 Lines of Code

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.

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

Stay Connected!

Receive notifications about new posts and resources straight into your inbox!
SUBSCRIBE
close-link