Butter Knife In Android

Posted By : Ankita Singh | 17-Oct-2016

Butter knife in Android

Butter knife a library by jakewharton and is used for injecting views.The @Bind annotation is used to bind views or inject views and perform the cast of the correct type.

@OnClick(R.id.pagerStarted) is used to add ClickListener to the views.

Add the given below dependency to your build.gradle file

compile 'com.jakewharton:butterknife:7.0.1'

Don't forget to initialize the butter knife in oncreate : 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    ButterKnife.bind(this);
    initViews();
}

 

How to bind views or inject views :-

for  e.g.


@Bind(R.id.wePager)
ViewPager wePager;
SlidePagerAdapter mPagerAdapter;
@Bind(R.id.pagerStarted)
Button pagerStarted;

how to add on click listener :-

@OnClick({R.id.numChange, R.id.newNum})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.numChange:
            if (ConnectionCheck.isConnectionAvailable(ChangeNumber.this)) {
                changeNumberCall();
            } else {
                Toast.makeText(ChangeNumber.this, R.string.internet_check, Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

Features provided by butter knife :-

  • Binding views and other resources
  • Event listeners
  • Recycler view implementation

Goal :-

This library help developers like us to write better code and clean code.

Pros :-

  • No need to replace and activity.
  • Injection for clcik listeners are available.
  • Provide injection in adapter also
  • Provide injection in fragment

Cons :-

  • Don't provide injection in pojo.

 

THANKS

About Author

Author Image
Ankita Singh

Ankita is an Android Application Developer. She has experience in developing android application by using Java and xml.

Request for Proposal

Name is required

Comment is required

Sending message..