Android Learning Note-Butterknife 8.0 Annotated usage Introduction

Source: Internet
Author: User

Objective:

App project development Most of the time is mainly UI page, when we need to call a lot of Findviewbyid and Setonclicklistener and other code, the control of the less time we can accept, the control more often there will be a way to hit the keyboard impulse. So this time we think we can use annotations to let us out of this heavy work, but also to make the code more concise, easy to maintain, today we mainly learn to focus only on the view, Resource, action annotation Framework butterknife.

Butterknife Introduction

Butterknife is a view, Resource, Action injection framework that focuses on the Android system.

Official website: http://jakewharton.github.io/butterknife/

github:https://github.com/jakewharton/butterknife/

Butterknife comparison before and after use:

See how we did it before using the view annotations

1.) Before using
 Public classExampleactivityextendsappcompatactivity {Private Final StaticString TAG = exampleactivity.class. Getsimplename ();    String Butterknifestr;    Drawable butterknifedrawable;    Button butterknifebtn;    ImageView Butterknifeiv; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_butter_knife);        Initresource ();    Initviews (); }    Private voidinitviews () {butterknifebtn=(Button) Findviewbyid (R.id.btn_butter_knife); Butterknifebtn.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {log.e (TAG,"Onbutterknifebtnclick");        }        }); Butterknifeiv=(ImageView) Findviewbyid (R.id.iv_butter_knife);        Butterknifebtn.settext (BUTTERKNIFESTR);    Butterknifeiv.setimagedrawable (butterknifedrawable); }    Private voidInitresource () {butterknifestr=getString (R.string.title_btn_butter_knife); Butterknifedrawable=getdrawable (R.mipmap.ic_launcher); }}

2.) After use
 Public classButterknifeactivityextendsappcompatactivity {Private Final StaticString TAG = butterknifeactivity.class. Getsimplename (); PrivateUnbinder Unbinder;    @BindString (R.string.title_btn_butter_knife) string butterknifestr;    @BindDrawable (r.mipmap.ic_launcher) drawable butterknifedrawable;    @BindView (R.id.btn_butter_knife) Button butterknifebtn;    @BindView (R.id.iv_butter_knife) ImageView Butterknifeiv; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_butter_knife); Unbinder= Butterknife.bind ( This);    Initviews (); }    Private voidinitviews () {butterknifebtn.settext (BUTTERKNIFESTR);    Butterknifeiv.setimagedrawable (butterknifedrawable); } @OnClick (R.id.btn_butter_knife) Public voidOnbutterknifebtnclick (view view) {LOG.E (TAG,"Onbutterknifebtnclick"); } @Overrideprotected voidOnDestroy () {Super. OnDestroy ();    Unbinder.unbind (); }}

3.) Butterknife Advantages

Analyze the advantages of Butterknife by using the above comparison before and after

    • Powerful view binding and click event handling to simplify code and improve development efficiency
    • Easy handling of Viewholder binding issues in Adapter
    • Run without impact on app efficiency, easy to use configuration
    • Code clear, readable

After using before and after the comparison has not felt very easy to use. Next, how do you use it?

Butterknife How to use: 1.) Add the following configuration to the Build.gradle of project
Buildscript {  repositories {    mavencentral ()   }  dependencies {    classpath ' com.neenbedankt.gradle.plugins:android-apt:1.8 '  }}

2.) Add the following configuration to the Build.gradle of module
Apply plugin: ' Com.neenbedankt.android-apt ' Android {  ...} dependencies {  compile ' com.jakewharton:butterknife:8.1.0 '  apt ' com.jakewharton:butterknife-compiler : 8.1.0 '}

3.) Inject and reset injection

Activity

class extends Activity {  @BindView (r.id.title) TextView title;  @BindView (r.id.subtitle) TextView subtitle;  @BindView (r.id.footer) TextView footer;    Public void onCreate (Bundle savedinstancestate) {    super. OnCreate (savedinstancestate);    Setcontentview (r.layout.simple_activity);    Butterknife.bind (this);     // TODO Use fields ...   }}

Fragment: Due to different view lifecycles, it is required in Oncreateview bind, Ondestroyview unbind

 Public classFancyfragmentextendsFragment {@BindView (r.id.button1) Button button1;  @BindView (R.id.button2) Button button2; PrivateUnbinder Unbinder; @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View View= Inflater.inflate (r.layout.fancy_fragment, container,false); Unbinder= Butterknife.bind ( This, view); //TODO Use fields ...    returnview; } @Override Public voidOndestroyview () {Super. Ondestroyview ();  Unbinder.unbind (); }}

Viewholder

 Public classMyadapterextendsBaseadapter {@Override PublicView GetView (intposition, view view, ViewGroup parent)    {Viewholder holder; if(View! =NULL) {Holder=(Viewholder) View.gettag (); } Else{View= Inflater.inflate (R.layout.whatever, parent,false); Holder=Newviewholder (view);    View.settag (holder); } holder.name.setText ("John Doe"); // etc...    returnview; }  Static classViewholder {@BindView (r.id.title) TextView name;    @BindView (r.id.job_title) TextView jobtitle;  PublicViewholder (view view) {Butterknife.bind ( This, view); }  }}

4.) View injection @BindView, @BindViews
@BindView (R.id.btn_butter_knife)    Button butterknifebtn;    @BindViews ({r.id.tv_butter_knife1,r.id.tv_butter_knife2,r.id.tv_butter_knife3})    List<TextView> Textviews;

5.) Resource Injection
@BindString (R.string.title_btn_butter_knife) string butterknifestr;//string Annotations Use@BindDrawable (r.mipmap.ic_launcher) drawable butterknifedrawable;//drawable Annotations using@BindBitmap (r.mipmap.ic_launcher) Bitmap butterknifebitmap;;//bitmap Annotations using@BindArray (R.array.day_of_week) String weeks[];//Array@BindColor (r.color.colorprimary)intColorprimary;//Color Annotations Use@BindDimen (r.dimen.activity_horizontal_margin) Float spacer;

6.) Single Event injection

A control that specifies an event callback

    /*** with Parameters*/@OnClick (R.id.btn_butter_knife) Public voidOnbutterknifebtnclick () {}/*** with Parameters*/@OnClick (R.id.btn_butter_knife) Public voidOnbutterknifebtnclick (view view) {LOG.E (TAG,"Onbutterknifebtnclick"); }    /*** with parameters *@paramButton*/@OnClick (R.id.btn_butter_knife) Public voidOnbutterknifebtnclick (Button button) {log.e (TAG,"Onbutterknifebtnclick"); }

You can also specify an event callback for multiple controls

   /**      * Two different buttons are corresponding Onbutterknifebtnclick event callback     *     @param  button     */      @OnClick ({r.id.btn_butter_knife, r.id.btn_butter_knife1})    publicvoid  Onbutterknifebtnclick (Button button) {        "Onbutterknifebtnclick");    }

Custom controls do not pass IDs or can be bound to their own events

 Public class extends Button {  @OnClick  publicvoid  OnClick () {    //  TODO do something!   }}

7.) Multi-Event callback

Some view listener have multiple callback methods, such as EditText add Addtextchangedlistener

Edittext.addtextchangedlistener (NewTextwatcher () {@Override Public voidBeforetextchanged (Charsequence S,intStartintCountintAfter ) {} @Override Public voidOnTextChanged (Charsequence S,intStartintBefore,intcount) {} @Override Public voidaftertextchanged (Editable s) {}});

You can use the annotation method to change to the following

@OnTextChanged (value = r.id.nameedittext, callback =OnTextChanged.Callback.BEFORE_TEXT_CHANGED)voidBeforetextchanged (Charsequence S,intStartintCountintAfter ) {} @OnTextChanged (value= R.id.nameedittext, callback =OnTextChanged.Callback.TEXT_CHANGED)voidOnTextChanged (Charsequence S,intStartintBefore,intcount) {} @OnTextChanged (value= R.id.nameedittext, callback =OnTextChanged.Callback.AFTER_TEXT_CHANGED)voidaftertextchanged (Editable s) {}

8.) Selective injection

By default, both @ Bind and listener are required, and if Target view is not found, an error is made. In order to suppress this behavior, you can use @Optional annotations to Mark field and method, so that injection becomes selective, If TargetView exists, it is injected and does not exist, then nothing is done. Or use the @nullable in Android's "support-annotations" Library to decorate

void onmaybemissingclicked () {  //  TODO ...}

9.) butterknife.apply () function

You can modify the view collection element or the action, setter, and property of a single view by using the Butterknifeapply () function

butterknife.apply (Nameviews, DISABLE); Butterknife.apply (Nameviews, ENABLED,false);Static FinalButterknife.action<view> DISABLE =NewButterknife.action<view>() {@Override Public voidApply (view view,intindex) {view.setenabled (false); }};Static FinalButterknife.setter<view, boolean> ENABLED =NewButterknife.setter<view, boolean>() {@Override Public voidSet (view view, Boolean value,intindex)  {view.setenabled (value); }}; Butterknife.apply (Nameviews, View.alpha,0.0f);

10.)butterknife. FindByID ()

Butterknife also provides the FindByID function, which allows you to obtain the view in activity, Dialog, and view through FindByID (), and is a generic type that does not require a strong

Null== = Butterknife.findbyid (view, R.id.photo);

Butterknife automatically generated plug-in installation:

In the androidstudio->file->settings->plugins-> search Zelezny download add on the line, you can quickly generate the corresponding component instance object, do not write manually. When used, right--->generate--generate butterknife injections on the activity or Fragment or Viewholder layout resource code for which you want to import annotations, and then the selection box that appears.

Plugin GitHub Address: Https://github.com/avast/android-butterknife-zelezny

Here's a flowchart for using

Reference Link: http://www.cnblogs.com/whoislcj/p/5620128.html

http://jakewharton.github.io/butterknife/javadoc/

Android Learning Note-Butterknife 8.0 Annotated usage Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.