Sunday 9 August 2015

findViewById, Butter Knife to rescue


As an android developer you must have written a lot of code in onCreate [in Activity] or onCreateView[in Fragment]  to get the reference of views defined in layout xml files. For example to get the reference of username EditText and login Button from fragment_login.xml we do:

    EditText etUsername;
    Button btLogin;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
 
         etUsername=(EditText) view.findViewById(R.id.edittext_username);
         btLogin=(Button)view.findViewById(R.id.button_login);
 
        return view;

    }

if our application has lot of screen and views, writing such boilerplate code wastes a lot of time and make our classes look ugly.

ButterKnife is a small view injection library from Jake Wharton  which make the whole process easier with very few lines of code. To use ButterKnife  in your app you first need to add the dependency to you app module's gradle.build file as follows

dependencies {
 
    compile 'com.jakewharton:butterknife:7.0.1'
}

Once the dependency is added, you can use the Bind annotation to bind the Views by specifying their xml view ids.


   @Bind(R.id.editTextUsernameFragmentLogin)    EditText editTextUsername;
   @Bind(R.id.buttonLoginFragmentLogin)     Button buttonLogin;
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
     
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, view);
     
        return view;
    }

our onCreateView  has become a lot cleaner now. We just has to inform the ButterKnife which Id we want to bind and type and name of the variable and with ButterKnife.bind(this,view) it will do the rest for us.

We can also set the onClickListener on views with OnClick annotation. as

 @OnClick(R.id.buttonLoginFragmentLogin)
  public void onLogin() {
      //onLogin  
    }

Do forget to unbind the views in onDestroyView in case of fragment

    @Override
     public void onDestroyView() {
         super.onDestroyView();
         ButterKnife.unbind(this);
     }


That's it about view injection. Hope this will help you in writing clean code with less effort.