Butter Knife In Android
Posted By : Ankita Singh | 17-Oct-2016
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankita Singh
Ankita is an Android Application Developer. She has experience in developing android application by using Java and xml.