Android Butterknife
I came across butterknife few weeks back when I was going through the resumes and I started reading about dependency injections in android. Butterknife injects code at compile time and almost similar to the java annotations .
I have found it very useful and easy to use in android but very few of us know about it . So lets try and use it and try to understand if it is helpful or not .
WHY SHOULD WE USE IT ??
It reduces code and make developer life easy . Also help in maintain code readability.
Prerequisites
Download the jar
Click here to download jar
If link dose not work do drop mail or comment so that I can share the latest version 4.0.1
Create a Android project and the lib as the usual process
Add annotaions
Add Factory Path Jar
Once we are done till here we are full set to use butter knief
Now here comes the main QUESTION
Lets take a look at normal way we code in Android till now .
Declaring variables
ImageView mTeamOne;
ImageView mTeamTwo;
Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_current_matched, container, false);
mTeamOne = (ImageView) view.findViewById(R.id.imageview_teamone);
mTeamTwo = (ImageView) view.findViewById(R.id.imageview_teamtwo);
mButton = (ImageView) view.findViewById( R.id.imageview_button);
}
But there's a smart way butter knife provides
public class MainActivity extends Activity {
@InjectView(R.id.button1) Button button_one;
@InjectView(R.id.button2) Button button_two;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
}
Setting onClickListeners
Normal way to do it.
button_one.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
button_two.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
ButterKnief Smater way
@OnClick(R.id.button1)
public void attemptLogin() {
// Logic
}
Now lets see how we can set listeners for multiple views
@OnClick({R.id.button1 , R.id.button2})
public void doOnClick(View v){
switch (v.getId()) {
case R.id.button1:
showToast(v, "One");
break;
case R.id.button2:
showToast(v, "Two");
break;
default:
break;
}
}
Performance
RoboGuice and Dagger does the same thing but make a performance impact as it's done on runtime using reflection and in ButterKnief its done at compiletime .
Thanks for reading and hope it helped U..
Happy Coding...
No comments:
Post a Comment