Butterknife Github library implementation

androidlearninghub, android learning hub, butterknife, butter knife, butterknife github
Image Credit - Jack Warton/ GitHub

We have already shared most used android libraries right now. You can read the details below.
Most used libraries in android

And Butterknife in Github is one of them. Android ButterKnife library is used to inject views into activities and fragments. In this tutorial, we will see how to implement the Butterknife library in an Android Application using Android Studio.

Step 1: Create New Project in Android Studio


Step 2: Add below dependencies in you project Gradle


dependencies {
    ...

    // butterknife dependency

    compile 'com.jakewharton:butterknife:8.8.1'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

Step 3: Create a linear layout with EditText and Button in activity_main.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lbl_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter your email"
        android:textAllCaps="true" />

    <EditText
        android:id="@+id/input_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_enter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dimen_20"
        android:text="@string/enter" />

</LinearLayout>

Step 4: In MainActivity.java, use @BindView to bind text and edit text views with a variable. Use @OnClick to bind button view with the method to do operations.


    @BindView(R.id.lbl_title)
    TextView lblTitle;

    @BindView(R.id.input_name)
    EditText inputName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // bind the view using butterknife
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_enter)
    public void onButtonClick(View view) {

        Toast.makeText(getApplicationContext(), "Your text is: " + inputName.getText().toString(),
                Toast.LENGTH_SHORT).show();

    }


Step 5: Run the Application.

You will get the desired output. 

------------------------------------------------------------------------------------------------------

Follow Android Learning Hub for latest updates and tutorials of Android.

------------------------------------------------------------------------------------------------------



Comments