Android Studio tip 3— FindViewById

Federico Palmieri
AndroidPub
Published in
3 min readFeb 6, 2017

--

Today, it’s View time. Let’s speak about how to speed up the process of retrieving the instance of the defined views from a xml layout file.

I’m pretty sure that every android developer starts hating quite soon the repetitive task of writing findviewbyid for each view defined in the layout file. If you don’t hate it, then let’s put it in another way, it’s a waste of time!

Some of you might be using ButterKnife to avoid the cast that findviewbyid implies (probably for some other reasons too). Even though this helps, it doesn’t remove the pain of annotating each single field with its own id.

How many times have you done back and forth from your layout and your java class just because you forgot the id of one of the views? Let’s stop it!

We have two different ways we can follow wherever you’re using plain findviewbyid or ButterKnife.

With ButterKnife

If you are a user of ButterKnife, then you probably want to get close to Android ButterKnife Zelezny.

Android ButterKnife Zelezny

This plugin will allow you to simply generate the ButterKnife annotations, and for Activities and Fragments it will also add the call to the ButterKnife.bind(…). In a View instead, you need to add that call yourself.

  • Activity
  • Fragment
  • View

Without ButterKnife

If you are not using ButterKnife, then you might want to take in consideration FindViewByMe.

FindViewByMe

Edit: I managed to push in the repository the support of the fragments and custom views and, as today, the developer published v1.3.5 of the plugin that solves the issues mentioned below. I Will update the GIFs accordingly.

This good plugin is still under development and doesn’t work well with fragments and custom views yet. In an Activity, it will do everything for you without having to manually define and assign the views that are inside the layout file. In fragments and custom views, you’ll need slightly more effort.

  • Activity

As mentioned before, it doesn’t work well with fragments yet, but we can make it work anyway. You’ll need to override onCreate, as the plugin only works by calling the generated method inside an onCreate method.

  • Fragment

In a View, it works pretty much the same as in a Fragment. You can’t override onCreate, but you can cheat by creating a fake onCreate() method.

  • View

If you feel brave, you can help the developer of this plugin to improve it and fix the above-mentioned issues by forking the repository here.

Thanks and, as usual, please do let me know your opinion!

--

--

Federico Palmieri
AndroidPub

Software engineer. Tech enthusiast, football fan, beer lover.