Butterknife Basic Use

Source: Internet
Author: User

Butterknife basically uses butter knife to handle field and method bindings. Configuration: When configured with Gradle, add:
Compile ' com.jakewharton:butterknife:6.1.0 '
Note is added in module:appGradle file. Plus you don't have to run any commands, just sync it and see Butterknife in the external libraries. function 1: No more writing Findviewbyid ().Previous:
MTextView1 = (TextView) Findviewbyid (r.id.butter_text_view_1);
It is now possible to do this: first add annotations to the variable declaration:
@InjectView (r.id.butter_text_view_2) TextView mTextView2;
If the ID cannot be found, the error will be at compile time. Then call Butterknife.inject () after setting up the layout:
@Override protected void onCreate (Bundle savedinstancestate) {    super. OnCreate (savedinstancestate);    Setcontentview (r.layout.demo_butter_knife);      // using butter knife    Butterknife.inject (this);}
The View object can then be used directly. It is important to note that the view variable declaration cannot bePrivateOrStaticIn addition to the activity, you can provide additional view Root to get the object (execute injection). It can also be used to simplify the Viewholder inside the adapter: Butterknife in FragmentYou can also use Butterknife to get view in fragment:
 Public classSimplefragmentextendsFragment {@InjectView (r.id.fragment_text_view) TextView Mtextview;  Publicsimplefragment () {} @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate ) {View View= Inflater.inflate (R.layout.fragment_simple, container,false); Butterknife.inject ( This, view); Mtextview.settext ("TextView in Fragment is found!"); returnview; }}

butterknife in Adapter viewholderAdapter has a common optimization strategy, which is to use viewholder to reduce the repeated invocation of Findviewbyid (). Previously written related blog posts: http://www.cnblogs.com/mengdd/p/3254323.html After using Butterknife, the use of Viewholder can be turned into this:
@Override PublicView GetView (intposition, View Convertview, ViewGroup parent)        {Viewholder holder; if(Convertview = =NULL) {Convertview= Minflater.inflate (R.layout.person_item_layout,NULL); Holder=NewViewholder (Convertview);        Convertview.settag (holder); } Else{Holder=(Viewholder) Convertview.gettag (); } Person Person=GetItem (position); if(NULL!=Person )            {Holder.name.setText (Person.getname ());            Holder.age.setText (String.valueof (Person.getage ()));            Holder.location.setText (Person.getlocation ());        Holder.work.setText (Person.getwork ()); }         returnConvertview; }     Static classViewholder {@InjectView (r.id.person_name) TextView name;        @InjectView (r.id.person_age) TextView age;        @InjectView (r.id.person_location) TextView location;         @InjectView (r.id.person_work) TextView work;  PublicViewholder (view view) {Butterknife.inject ( This, view); }    }
You can see that the Viewholder class adds a construction method with a parameter view, marking each field with annotations, and no longer need toGetView ()Method calls the Findviewbyid () method. function 2: No more writing Setonclicklistener ().Like the previous:
    Finishbutton.setonclicklistener (new  View.onclicklistener () {        @Override        public  void  OnClick (View v) {            finish ();        }    });
Can now be written as:
    @OnClick (R.id.basic_finish_a_button)    void  Finisha (view view) {        finish ();    
Note that the method here still cannot bePrivateAndStaticAnd can have a parameter view or not. All listener parameters are optional, can be written, can not be written. and write a specific subclass can be written directly, such as parameter view can be written as a button, where the cast is automatically completed. Note that you still need to callButterknife.inject (this);Otherwise, the event binding is unsuccessful. Forget to call Butterknife.inject (this); for Findview, it will be an error, but it will not be an error for the binding event, but nothing happens. In addition to clicking on event @onclick, there is also a click of the ListView@OnItemClick, CheckBox's@OnCheckedChangedAnd so on. You can specify more than one ID at a time, binding an event-handling method to multiple view, such as:
// You can bind listener to multiple views @OnClick ({r.id.button_enable, r.id.button_disable, R.id.button_alpha_0, r.id.button_alpha_1}) void editviewsclicked () {    Toast.maketext (This, "you click the button!" , Toast.length_short). Show ();}
Feature 3: Build the View List: Put multiple view togetherMultiple view can be obtained at the same time, placed in a list:
@InjectViews ({r.id.label_first_name, r.id.label_middle_name, r.id.label_last_name}) List<TextView> labelviews; @InjectViews ({r.id.first_name, r.id.middle_name, r.id.last_name}) List<EditText> Nameviews;
Note that IDs are separated by commas, curly braces surround, and parentheses are outside. The  apply () method allows you to set values in batches for a group of objects. The Apply () method has 3 forms:
 public  static  <t "extends  view> void  apply (list<t> List, action<? super  t> action)  public  static  <t extends  View, v> void  Apply (list<t> List, setter<? super  T, V> setter, V value)  public  static  <t extends  View, v> void  Apply (list<t> List, property<? super  T, v> Setter, V value) 
That is, action, setter and property three kinds. Where both the action and setter are Butterknife classes, you need to inherit, write your own subclass implementation, and then pass in the object. The third parameter of the setter can specify what value to set to. property is a class in Android: https://developer.android.com/reference/android/util/Property.html specific use can be found in the example: https:// github.com/mengdd/androidbutterknifesample/blob/master/app/src/main/java/com/example/mengdd/butterknifesample/ Viewlistactivity.java Other practical Methods 1. Injection Reset (injection Rest):can be usedReset ()The Butterknife method sets the view reference injected as NULL. For example, in Fragment's Oncreateview () call the Butterknife.inject () method injects some view,Ondestroyview ()You want to set them to NULL, you can call them directly.Butterknife.reset (this);Method. 2. Selective injection (Optional injection):By default, both @InjectView and listener are required, and if Target view is not found, an error is made. To suppress this behavior, you can use@OptionalAnnotations to Mark field and method, let the injection become selective, if targetview exists, then inject, do not exist, then do nothing. This @optional annotation is useful when the layout is reused. 3. Multi-method Listener (Multi-method Listeners):Some view listener have multiple callback methods, such as the Onitemselectedlistener of spinner:
Mspinner.setonitemselectedlistener (new  Adapterview.onitemselectedlistener () {    @Override     publicvoidintlong  ID) {    }     @Override      publicvoid onnothingselected (adapterview<?> parent) {    }});

Method annotations can be used to bind to any one of these methods. Each annotation has a default callback that specifies what method it binds to, and can be specified as a specific method by the callback parameter. For example: No callback is specified, The default corresponds to the Onitemselected () method:
@OnItemSelected (r.id.my_spinner)     // default callback:item_selected void onitemselected (int  position) {    Toast.maketext (This, "position:"+  Position, Toast.length_short). Show ();}
Specifies the callback, corresponding to the onnothingselected () method:
@OnItemSelected (value = R.id.my_spinner, callback = OnItemSelected.Callback.NOTHING_SELECTED)void onnothingselected () {    Toast.maketext (This, "Nothing", Toast.length_short). Show (); 
Note that as long as there is data in spinner, the No. 0 data is selected by default, so if you want to enter the Onnothingselected () method, you need to empty the data in the adapter. For a complete example, see: HTTPS://GITHUB.COM/MENGDD /androidbutterknifesample/blob/master/app/src/main/java/com/example/mengdd/butterknifesample/ Spinneractivity.java 4.findById () methodButterknife.findbyid ()Can be used to get activity,dialog or any of the view.butterknife in view to automatically complete the type conversion, so get out of the explicit strong turn, directly assigned to the specific view type reference. Resources:sample Project:https://github.com/mengdd/androidbutterknifesample introduction:http:// Jakewharton.github.io/butterknife/java doc:http://jakewharton.github.io/butterknife/javadoc/github:https:// Github.com/jakewharton/butterknife

Butterknife Basic Use

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.