Butterknife can eliminate the steps of control Findviewbyid and improve development efficiency.
Usage:
1. Add Dependencies:
Compile ' com.jakewharton:butterknife:5.1.1 '
2. Use in activity:
Public classMainactivityextendsappcompatactivity {//use Butterknife to initialize the control (eliminating the use of the Findviewbyid () method, which improves development efficiency)@InjectView (r.id.tv)protectedTextView TV; @InjectView (R.ID.IV)protectedImageView IV; @InjectView (R.ID.BTN)protectedbutton button; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Register ButterknifeButterknife.inject ( This); Tv.settext ("Hello TextView"); Iv.setimageresource (R.mipmap.ic_launcher); } //trigger event in the Click () method when r.id.btn represents a control@OnClick (R.ID.BTN)protected voidClick () {Tv.settext ("Button Clicked"); }}
3. Use in Fragment:
Public classMainfragmentextendsFragment {//use Butterknife to initialize the control (eliminating the use of the Findviewbyid () method, which improves development efficiency)@InjectView (r.id.tv) TextView TV; @InjectView (R.ID.IV) ImageView IV; @InjectView (R.ID.BTN) button button; @Nullable @Override PublicView Oncreateview (layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) { View View= Inflater.inflate (R.layout.activity_main, container,false); //Register Butterknife (use Butterknife in fragment to specify a root View)Butterknife.inject ( This, view); returnview; } @Override Public voidonviewcreated (view view, @Nullable Bundle savedinstancestate) {Tv.settext ("Hello Butterknife"); Iv.setimageresource (R.mipmap.ic_launcher); } //trigger event in the Click () method when r.id.btn represents a control@OnClick (R.ID.BTN) Public voidClick () {Tv.settext ("Button Clicked"); }}
Note: No matter the method or the control, as long as the annotation butterknife, you can not use private or static decoration!!
Use of the "Android-frame" butterknife