Butter Knife: ease to bind view in activity
ButterKnife is an open source that eases the way to bind view in activity class.
Below is the example:
1. In build gradle,
2. Suppose there are two buttons having id - android:id="@+id/hiBtn" android:id="@+id/byeBtn"
3. In activity .java class,
a. Initialize your binding button variable as-
For Activity class, in onCreate() method,
Below is the example:
1. In build gradle,
compile 'com.jakewharton:butterknife:8.5.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
2. Suppose there are two buttons having id - android:id="@+id/hiBtn" android:id="@+id/byeBtn"
3. In activity .java class,
a. Initialize your binding button variable as-
@BindView(R.id.hiBtn) Button hiBtn; @BindView(R.id.byeBtn) Button byeBtn;b.
For Activity class, in onCreate() method,
ButterKnife.bind(this);For Fragment class, in onCreateView() method
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
ButterKnife.bind(this, view);
c. And the button click event as,@OnClick(R.id.hiBtn) public void sayHi(Button hiBtn) { hiBtn.setText("Hello!"); } @OnClick(R.id.byeBtn) public void sayBye(Button byeBtn) { byeBtn.setText("Bye!"); }Butter Knife comes with the flexibility to bind color, drawable, etc. using annotation like @BindColor, @BindDrawable.
Also, in case there are buttons having same functionality, ButterKnife provides @OnClick annotation for them as below:
@OnClick( {R.id.buttonOne, R.id.buttonTwo, R.id.buttonThree, R.id.buttonFour, R.id.buttonFive, R.id.buttonSix, R.id.buttonSeven, R.id.buttonEight, R.id.buttonNine}) public void buttonClicked(Button button) { }
Comments
Post a Comment