Tuesday, April 15, 2014

Using Butter Knife in Android

Butter Knife  is View "injection" library for Android which uses annotation processing to generate the code for you.

we should follow these steps

  • Eliminate findViewById calls by using @InjectView on fields.
  • Group multiple views in a list using @InjectViews. Operate on all of them at once with actions, setters, or properties.
  • Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
for an example create a project and have a layout as follows

example.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Insert Username" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Insert Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login" />

</LinearLayout>

correspondingly write the Activity code as follows
SimpleActivity.java 

import static android.widget.Toast.LENGTH_SHORT;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class SimpleActivity extends Activity {
       @InjectView(R.id.editText1)
EditText username;
@InjectView(R.id.editText2)
EditText password;
@InjectView(R.id.button1)
Button login;
@OnClick(R.id.button1) void sayLogin() {
Toast.makeText(this, "Hello!"+" yours username is "+username.getText().toString()+" & Yours password is "+password.getText().toString(), LENGTH_SHORT).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
ButterKnife.inject(this);

}
}


beside this write application class as follows

import android.app.Application;
import butterknife.ButterKnife;

public class SimpleApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ButterKnife.setDebug(BuildConfig.DEBUG);
}
}


and include it at manifest as 

 <application
        android:name="com.packagenamee.SimpleApp"  .....


finally run the code and see a login screen, Happy coding

download the butter knife jar from 

http://jakewharton.github.io/butterknife/

on having problems and issues follow