Android ButterKnife Example

Filed Under: Android

In this tutorial we’re going to discuss the Android ButterKnife tool and look into it’s usages.

Android ButterKnife

ButterKnife, Android ButterKnife Example
Android Butterknife is a view binding tool that uses annotations to generate boilerplate code for us. ButterKnife is developed by Jake Wharton at Square and is essentially used to save typing repetitive lines of code like findViewById(R.id.view) when dealing with views, thus making our code look a lot cleaner.

ButterKnife Android Dependency

To use ButterKnife in android application we need to add the following dependency to our build.gradle file.


compile 'com.jakewharton:butterknife:6.1.0'

Android ButterKnife inject

Before using any views, we need to inject ButterKnife by adding below code in onCreate() method of the activity.


ButterKnife.inject(this);

Note: When using fragments we need to specify the source of the view in the onCreateView() as below.


View view = inflater.inflate(R.layout.sample_fragment, null);
ButterKnife.inject(this, view);

Android ButterKnife Example

A simple activity example with ButterKnife is shown below.


public class MainActivity extends Activity {  
  @InjectView(R.id.sample_text) TextView textView;
  @InjectView(R.id.sample_button) Button button;

  @Override 
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.inject(this);
    textView.setText("You can change this view accordingly");

    @OnClick(R.id.click_button) 
    void buttonClick() {  
    //..you don't even need the line @InjectView(R.id.click_button) if this button isn't being used else where
}

  }
}

In the above code snippet, @OnClick is the ButterKnife annotation that removes the need for the setOnClickListener method. The method below is automatically configured to that annotation. An argument inside the method is optional.

We can specify multiple IDs in a single binding for common event handling as shown below.


@OnClick({ R.id.btn1, R.id.btn2, R.id.btn3 })
public void commonMethod(Button button) {
  button.setText("Text specified here would be same for all");
}

In the above code a specific type of view (Button) is automatically casted.

An example of implementing ButterKnife in fragments is given below.


public class SomeFragment extends Fragment {

    @InjectView(R.id.textView) 
    TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {

        ViewGroup rootView = (ViewGroup) inflater
                .inflate(R.layout.some_layout, container, false);

        ButterKnife.inject(this, rootView);

        //Work on the TextView
        someTextView.setVisibility(View.VISIBLE);
        return rootView;
    }

    @OnClick({ R.id.imageView, R.id.someTextView })
    public void doSomething() {
        //Do something when imageView or someTextView is clicked.
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //Set views to null:
        ButterKnife.reset(this);
    }
}

For a ListView itemClick the following annotation is used.


@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
  // TODO ...
}

Note: An exception will be raised if the target view is not found. To suppress this exception we can add a @Nullable annotation, thereby making it an optional binding.

This brings an end to ButterKnife in android short tutorial. For a complete example, please read Android Notification.

Reference: ButterKnife at GitHub

Comments

  1. d says:

    fot this

    compile ‘com.jakewharton:butterknife:6.1.0’

    try this instead

    *** implementation ‘com.jakewharton:butterknife:8.5.1’
    *** annotationProcessor ‘com.jakewharton:butterknife-compiler:8.5.1’

    and then in the mainactivity class

    change: ButterKnife.inject(this)
    for: **** ButterKnife.bind(this)

  2. Monika Sharma says:

    Hey am getting error while compiling butterknife plugin its error is below….

    Error:Execution failed for task ‘:app:javaPreCompileDebug’.
    > Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor. Please add them to the annotationProcessor configuration.
    – butterknife-6.1.0.jar (com.jakewharton:butterknife:6.1.0)
    Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior. Note that this option is deprecated and will be removed in the future.
    See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages