In this article we are learning about ButterKnife in android. This article explains the usage of the ButterKnife library to inject views into android application.
Introduction
ButterKnife is developed by Jake Wharton at Square and is used to save typing repetitive lines of code like findViewById(R.id.view) when dealing with views, this is making our code look a lot cleaner. It uses annotation processing.
This is the lightweight library to inject or bind views into an android application.
The @BindView annotation allows you to bind views and perform the cast to the correct type for you. The @@OnClick(R.id.yourid) annotation allows adding setOnClickListener to a view. You can optionally define the method parameter of the view in case you want it injected.
ButterKnife also includes findById methods for a View, Activity, or Dialog.
Steps for Add ButterKnife in our project:
Step -1 : Add dependency in build.gradle file
implementation “com.jakewharton:butterknife:6.1.0”
Step-2: Then we need to inject ButterKnife by adding below code in onCreate() method of the activity
ButterKnife.inject(this);
When we use fragment then we need to specify the source of the view in the onCreateView() like given below:
View view = inflater.inflate(R.layout.sample_fragment, null); ButterKnife.inject(this, view);
Example:
An Example of Implementing ButterKnife in activity :
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("The Code Hubs"); @OnClick(R.id.click_button) void buttonClick() { } } }
In above code, @OnClick() is a butterKnife annotation that removes the use of setOnClickListener() method. Using this you can directly make the button click like given above.
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("The Code Hubs"); }
In the above code a specific type of view (Button) is automatically casted.
An example of implementing ButterKnife in fragment:
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); } }