Step - 1: App this library to App level gradle
compile 'com.jakewharton:butterknife:6.1.0'
Step - 2 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ffffff" tools:context="cmsecomm.ecommerce.app.com.butterknife.MainActivity"> , <fragment android:name="cmsecomm.ecommerce.app.com.butterknife.PageFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/id1" /></LinearLayout>
Step - 3 : MainActivity.java
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Button;import android.widget.TextView; import butterknife.ButterKnife;import butterknife.InjectView;import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
Step - 4 : fragment-page.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ffffff" tools:context="cmsecomm.ecommerce.app.com.butterknife.MainActivity"> <TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000000" /> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> <Button android:id="@+id/btn3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /> </LinearLayout>
Step - 5 : PageFragment.java
import butterknife.ButterKnife;import butterknife.InjectView;import butterknife.OnClick; /** * Created by Divakar on 5/31/2017. */ public class PageFragment extends Fragment { @InjectView(R.id.tv1) TextView tv1; @InjectView(R.id.btn1) Button b1; @InjectView(R.id.btn2) Button b2; @InjectView(R.id.btn3) Button b3; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View itemView = inflater.inflate(R.layout.fragment_page, container, false); ButterKnife.inject(this, itemView); tv1.setText("This is Fragment"); return itemView; } @OnClick(R.id.btn1) void buttonClick() { tv1.setText("Fragment-Button1"); } @OnClick({R.id.btn2, R.id.btn3}) void performClick() { tv1.setText("Fragment-Button 2 & 3 mixed click"); } }