The most complete history of android use in Butterknife

Open source address
https://github.com/JakeWharton/butterknife
are interested can take a look at

Butterknife advantage of
strong binding Binding View event and resource files
on ease of use, excluding the time of the original binding of complexity
because most comments were at compile time, so it will not affect the efficiency of running
the code clear and legible relatively much stronger
how to use Butterknife?
dependent libraries and add plug-ins
to add plug-in

    File -> Settings -> Plugins -> Search ButterKnife, find Android ButterKnife Zeleany be installed reboot AndroidStudio 


Dependent libraries

If you want to use it Butterknife, is certainly going to be dependent libraries of
    the compile 'com.jakewharton: butterknife: 8.8.1'
    AnnotationProcessor 'com.jakewharton: butterknife-Compiler: 8.8.1'
understanding Butterknife annotation type
Butterknife latest version, provides us with a total of 25 comments. Which is divided into two types, one is the binding of the resource, another is the type of event listeners

Binding annotation, view, resources, and so on, a total of 13
name resolution
@BindViews bound to a plurality of view id list view of a variable @BindViews ({R.id.first_name, R.id.middle_name, R.id. } last_name) List <the EditText> nameViews;
@BindView bind a view of a variable view id @BindView (R.id.title) the TextView title;
@BindArray binding array array @BindArray (R.array.city String in) String [] the citys;
@BindBitmap binding image resource file, @BindBitmap (R.mipmap.wifi) Bitmap Bitmap;
@BindBool binding @BindBool true and false boolean (R.bool.boor)
@BindColor binding color @BindColor (R .color.red)
@BindDimen bundling size @BindDimen (R.dimen.spacer) the Float spacer;
@BindDrawable @BindDrawable binding Drawable (R.drawable.graphic) Drawable Graphic
@BindFloat binding the Float
@BindInt binding Int
@BindString bind a String id as String variables, @BindString (R.string.app_name) String msg
@BindAnim binding animated
@BindFont binding text font
binding events, a total of 12 event listener
name resolution
@OnClick click event
@ OnCheckedChanged selected, select cancel
@OnEditorAction soft keyboard function keys
@OnFocusChange focus changes
@OnItemClick Item is clicked event (Note that there is a pit, if the item there, which are clicked button controls these events, you need to set the controls property focusable to false )
@OnItemLongClick TEM press, returns true you can block onItemClick
@OnItemSelected Item selected events
@OnLongClick press event
@OnPageChange page change event
@OnTextChanged EditText inside the text change event
@OnTouch touch event
@Optional selective implantation, if the current object does not exist, it will throw an exception, in order to suppress the exception, you can add notes on what variables or methods, so that the injection becomes selective, View if the target is present, the injection does not exist, what = Not done following code
Activity in ButterKnife use in
data binding tag 13, Bind series
@BindAnim 
use as follows:

@BindAnim (R.anim.fade_in) Animation fadeIn;
. 1
2
@BindArray 
use as follows: 
Since the array the array can be defined in the resource file into a variety of data types, the following use

1:String array
    //数组:
    <string-array name="countries">
        <item>中国</item>
        <item>日本</item>
</string-array>
    @BindArray(R.array.countries) String[] countries;
2:Int array
    //数组:
    <integer-array name="phones">
        <item>12345</item>
        <item>43534</item>
    </integer-array>
    @BindArray(R.array.phones) int [] phones
3:Text array
    //数组:与stringArray类似
    <string-array name="countries">
        <item>中国</item>
        <item>日本</item>
    </string-array>
    @BindArray(R.array.options) CharSequence[] options;

. 4: Array the Type -----> android.content.res.TypeArray
    // array, TypeArray type is a hybrid form, that it is relatively complex:
    <String Array-name = "feed_icons">
        <Item> @ Color / colorAccent </ Item>
        <Item> @ dimen / dp_72 </ Item>
        <Item> @ the drawable / leak_canary_icon </ Item>
        <Item> @ the drawable / flashligth_drawable_btn </ Item>
        <Item> @ the drawable / ic_launcher_background </ Item >
        <Item> @ layout / encode </ Item>
    </ String-Array>
    @BindArray (R.array.icons) the TypedArray iconsThe;
 
@BindBitmap 
bind operation image

@BindBitmap (R.drawable.logo) Bitmap logo;
@BindBitmap (R.mipmap.ic_launcher) Bitmap mBitmap;
 
@BindBool 
value binding boolean type

// first define bool in the resource file,
<bool name = "isRun"> to true </ bool>

@BindBool (R.bool.isRun) Boolean isRun;
// but generally not carried out by use
 
@BindColor 
binding operation color, the same color can be bound to a single color, the same combination of colors may be bound form,

// binds single color:
// definition of color type:
<Color name = "colorAccent"> # FF4081 </ Color>
@BindColor (R.color colorAccent.) Int colorAccent;

//绑定颜色组合:使用ColorStateList类进行操作,定义一个button_view的selector
<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
            <item android:state_pressed="true"  
          android:color="#ffff0000"/> <!-- pressed -->  
        <item android:state_focused="true"  
          android:color="#ff0000ff"/> <!-- focused -->  
            <item android:color="#ff000000"/> <!-- default -->  
</selector>

// This will bind ColorStateList, and then set by setTextColor space
@BindColor (R.color. Button_view) ColorStateList greenSelector
 
@BindDimen

Binding size, int type sizes and type float

@BindDimen(R.dimen.sp_20) int gapxp;
@BindDimen(R.dimen.sp_20) float gapsp;
 
@BindDrawable 
Drawable的绑定

@BindDrawable (R.drawable.placeholder) Drawable placeholder
// There is another form, i.e. with a drawable attr used together, as characteristic attr, Tint colored mean
@BindDrawable (value = R.drawable.placeholder, tint = R .attr.colorAccent) 
Drawable tintedPlaceholder;
 
@BindFloat binding type float

<item name="whatever" format="float" type="dimen">1.1</item>
<item name="twelve_point_two" format="float" type="dimen">12.2</item>
    BindFloat(R.dimen.image_ratio) float imageRatio
BindFloat(R.dimen. twelve_point_two) float twelve_point_two
 
@BindFont 
绑定的是字体样式

BindFont (R.font.comic_sans) Typeface comicSans;
set style in the form of setTypeFace
 
@BindInt 
binding type int

BindInt (R.int.columns) int the Columns;
 
@BindString 
binding String type of resource

@BindString (R.string.app_name) String appName;
 
@BindView 
the id of the view control binding operation

@BindView(R.id.showArrayText)  TextView mView;
1
@BindViews

BindViews fact is an extended form of BindView, is mainly used to view a plurality of the same time, this can be used when loading BindViews be mounted in a set / array, so that when in use, form directly by subscripts use

BindViews ({R.id.title, R.id.subtitle}) List <the TextView> titlesList;
BindViews ({R.id.title, R.id.subtitle}) the TextView [] titlesArray;
// then titlesList.get (1) or titlesArray [1] to obtain
 
an event trigger using a form of annotation labels, 12 On series
@ OnCheckedChanged 
this property mainly for similar RadioButton, CheckedBox, its parent class CompoudButton type of control 
can be mainly the following three forms : Note: the name of the function can actually be a random value, but there are two forms of formal parameters

// first: only a formal parameter Boolean
@OnCheckedChanged (R.id.checkBox)
    void onChecked (Boolean the isChecked) {
        Toast.makeText (the this, "checkBox:" + the isChecked, Toast.LENGTH_SHORT) the .Show ();
}

//第二种:形式参数中有控件CompoundButton和boolean
@OnCheckedChanged(R.id.checkBox2)
void onCheckedChanged(CompoundButton compoundButton,boolean isChecked){
        Toast.makeText(this, "compoundButton111:"+compoundButton+"\tcheckBox:"+isChecked, Toast.LENGTH_SHORT).show();
}

// two third form of ID, if this time is not bound view, the default operation will bind
@OnCheckedChanged ({R.id.checkBox3, R.id.checkBox4})
void onCheckedChanged2 (CompoundButton compoundButton , boolean isChecked) {
        Toast.makeText (the this, "compoundButton2222:" + compoundButton + "\ TCheckBox:" + isChecked, Toast.LENGTH_SHORT) .Show ();
}
 
@ the OnClick 
the OnClick very simple, in fact, is a click event, but in ButterKnife click event parameters can not, you can also have a type ,, View is not bound View, you can also take effect

@OnClick(R.id.example) 
    void onClick() {
        Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
    }

@OnClick({R.id.topText,R.id.bottom_text})
    void onTextViewClick(View mView){
        Toast.makeText(BufferKnifeDemoActicity.this,((TextView)mView).getText().toString(),Toast.LENGTH_LONG).show();
}

// If it is in the custom view, like, this time, do not specify a specific ID.
{CustomBtn the extends the Button Class
        @Onclick
        public void onClick (View View) {
    }
}
 
@ OnEditorAction 
OnEditorAction primarily for the EditText against, setOnEditorActionListener should be noted that this method is not triggered when we click EditText, nor is it in our when EditText editing trigger, but after we finished editing click the Enter key on the soft keyboard will trigger 
because EditText TextView is inherited from, and therefore in the actual process, but also may have returned TextView

@OnEditorAction(R.id.example) boolean onEditorAction(KeyEvent key) {
    Toast.makeText(this, "Pressed: " + key, Toast.LENGTH_SHORT).show();
    return true;
 }

@OnEditorAction(R.id.example) boolean onEditorAction(TextView mTextView,int actionId,KeyEvent key) {
    Toast.makeText(this, "Pressed: " + key, Toast.LENGTH_SHORT).show();
    return true;
 }

// used in a manner specific reference OnEditorActionListener can use
 
@ OnFocusChange

This annotation is mainly derived from setOnFocusChangeListener, that is, its main role is also to be used for EditText

@OnFocusChange(R.id.example) void onFocusChanged(boolean focused) {
        Toast.makeText(this, focused?"Gainedfocus": "Lost focus", Toast.LENGTH_SHORT).show();
  }

// At the same time there is a two parameters are a function of the form
@OnFocusChange (R.id.example) void onFocusChanged (View MVIEW, boolean Focused) {
        Toast.makeText (the this, Focused "Gainedfocus":? "Lost Focus", Toast .LENGTH_SHORT) .Show ();
 }
 
@ onItemClick 
this annotation is mainly for AdapterView, that is similar to the ListView control uses this type of event, seemingly not in the actual inheritance and AdapterView RecycleView, and therefore can not use this comment

// first form: only one parameter position
    @OnItemClick (R.id.example_list) void in the onItemClick (int position) {
        Toast.makeText (the this, "the Clicked position" + + position, Toast.LENGTH_SHORT "!") The .Show ();
  }

// second form: There are four parameters
    @OnItemClick (R.id.example_list) void in the onItemClick (The AdapterView MVIEW, ItemView View, int position, Long NUM) {
        Toast.makeText (the this, "the Clicked position" + + position " ! ", Toast.LENGTH_SHORT) .Show ();
  }
 
@ OnItemLongClick 
this annotation is mainly for AdapterView, the type of event that is similar to the use of such controls ListView, seemingly not in the actual inheritance and AdapterView RecycleView, and therefore can not use this comment

// The first form: Parameter is only one position
    @ OnItemLongClick (R.id.example_list) void onItemClick (int position) {
        Toast.makeText ( "!" The this, "Clicked position" + + position, Toast.LENGTH_SHORT) .Show ();
  }

// second form: There are four parameters
    @OnItemLongClick (R.id.example_list) 
void in the onItemClick (The AdapterView MVIEW, ItemView View, int position, Long NUM) {
        Toast.makeText (the this, "the Clicked position" + + position " ! ", Toast.LENGTH_SHORT) .Show ();
  }
 
@ OnItemSelected 
for control is a subclass of AdapterView, that is similar to the use of OnItemSelectedListener ListView and Spinner in this category, use this comment

@OnItemSelected(R.id.example_list) void onItemSelected(int position) {
            Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
    }


@OnItemSelected(R.id.example_list) void onItemSelected(android.widget.AdapterView view, android.view.View mview, int position, long id) {
            Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
    }


@OnItemSelected (value = R.id.example_list, the callback = NOTHING_SELECTED)
    void onNothingSelected () {
        Toast.makeText the .Show () (the this,, Toast.LENGTH_SHORT "Nothing Selected!");
    }
 
@ OnLongClick 
OnLongClick very simple, in fact, that is, a click event, but in ButterKnife click event parameters can not, you can also have a type ,, View is not bound View, you can also take effect

@OnLongClick (R.id.example) 
    void onClick() {
        Toast.makeText(this, " OnLongClick!", Toast.LENGTH_SHORT).show();
    }

@OnLongClick ({R.id.topText, R.id.bottom_text})
    void onTextViewClick (View MVIEW) {
        Toast.makeText (BufferKnifeDemoActicity.this, ((the TextView) MVIEW) .getText (). ToString (), Toast.LENGTH_LONG ) .Show ();
}
 
@ OnPageChange 
OnPageChange annotation is mainly aimed at ViewPager to achieve, ViewPager there OnPageChangeListener ah


//使用方式一:
OnPageChange(R.id.example_pager) void onPageSelected(int position) {
  Toast.makeText(this, "Selected " + position + "!", Toast.LENGTH_SHORT).show();
}

//使用方式二:
@OnPageChange(value = R.id.example_pager, callback = PAGE_SCROLL_STATE_CHANGED)
void onPageStateChanged(int state) {
    Toast.makeText(this, "State changed: " + state + "!", Toast.LENGTH_SHORT).show();
}

//使用方式三:
@OnPageChange(value = R.id.example_pager, callback = PAGE_SCROLLED)
void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {

}
// main use is to be judged by the enumerated type, PAGE_SCROLLED, PAGE_SCROLL_STATE_CHANGED, PAGE_SELECTED
 
@ OnTextChanged 
mainly for TextWatcher controls to be implemented.

//使用方式一:
@OnTextChanged(R.id.example) void onTextChanged(CharSequence text) {
    Toast.makeText(this, "Text changed: " + text, Toast.LENGTH_SHORT).show();
}

//使用方式二:
@OnTextChanged(value = R.id.example, callback = BEFORE_TEXT_CHANGED)
void onBeforeTextChanged(CharSequence text) {
   Toast.makeText(this, "Before text changed: " + text, Toast.LENGTH_SHORT).show();
 }

// use three:
@OnTextChanged (value = R.id.example, the callback = AFTER_TEXT_CHANGED)
void onAfterTextChange (the Editable the editable) {
   Toast.makeText (the this, "After changed text:" + text, Toast.LENGTH_SHORT) the .Show ( );
 }
// and OnPagerChange use similar, which is also used to control the enumeration, BEFORE_TEXT_CHANGED, TEXT_CHANGED, AFTER_TEXT_CHANGED
 
@ OnTouch 
to design for all of the View have the onTouch event, as long as a subclass of View all You can use this comment

// use a:
    @OnTouch (R.id.example) Boolean OnTouch () {
            Toast.makeText (the this, "Touched!", Toast.LENGTH_SHORT) the .Show ();
            return to false;
    }
// use two, type parameters
    @OnTouch (R.id.example) Boolean OnTouch (View MVIEW, the MotionEvent Event) {
            Toast.makeText (the this, "! Touched", Toast.LENGTH_SHORT) the .Show ();
            return to false;
    }
// Precautions :
    // OnTouch for the match with onTouch system that meet the requirements of event delivery, so that there is a return value, and functions are also not required to have a return value.
 
@ Optional 
By default, @ Bind and listener injection are necessary, if target view was not found, an error is reported. In order to suppress this behavior, you can use annotations to mark the field and @Optional way for injecting become selected nature, if targetView exist, the injection does not exist, do nothing, or use Android's "support-annotations" library . the modified @Nullable

@OnClick @optional (R.id.subtitle) onSubtitleClick void () {}
. 1
ButterKnife is findById
ButterKnife findById function also provides, through findById () can be acquired Activity, Dialog, View of the View, and the generic type is not required strong turn

= LayoutInflater.from View View (context) .inflate (R.layout.thing, null); 
the TextView firstName = ButterKnife.findById (View, R.id.first_name); 
the TextView lastName = ButterKnife.findById (View, R.id. last_name); 
the ImageView Photo = ButterKnife.findById (View, R.id.photo); 
however, more than one method is already out of date, the official in fact, is no longer recommended to use these methods of

ButterKnife.apply () function is
a function of the type:
In this class ButterKnife overload on reaching a high number of apply method 12, thereby can be seen, apply the importance of this function. However, this function uses to doing it spread? ?
ButterKnife of apply () function on a single view or a view of the collection element Action, Setter Property and modifications. 
To know the way, we must first look at its function type parameter type it: as shown below:

@UiThread @SafeVarargs 
1:public static <T extends View> void apply(@NonNull List<T> list, @NonNull Action<? super T>... actions)

@UiThread @SafeVarargs 
2:public static <T extends View> void apply(@NonNull T[] array, @NonNull Action<? super T>... actions)

@UiThread
3:public static <T extends View> void apply(@NonNull List<T> list,@NonNull Action<? super T> action)

@UiThread
4:public static <T extends View> void apply(@NonNull T[] array, @NonNull Action<? super T> action)

@UiThread
5:public static <T extends View> void apply(@NonNull List<T> list,@NonNull Action<? super T> action)

6:
@UiThread @SafeVarargs 
public static <T extends View> void apply(@NonNull T view,@NonNull Action<? super T>... actions)

7:
@UiThread
public static <T extends View> void apply(@NonNull T view, @NonNull Action<? super T> action)

8: 
@UiThread
public static <T extends View, V> void apply(@NonNull List<T> list,@NonNull Setter<? super T, V> setter, V value)

9:
@UiThread
public static <T extends View, V> void apply(@NonNull T[] array,@NonNull Setter<? super T, V> setter, V value)

10: 
@UiThread
public static <T extends View, V> void apply(@NonNull T view,@NonNull Setter<? super T, V> setter, V value)

11: 
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // http://b.android.com/213630
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@UiThread
public static <T extends View, V> void apply(@NonNull List<T> list,@NonNull Property<? super T, V> setter, V value)

12 is     
@TargetApi (Build.VERSION_CODES.ICE_CREAM_SANDWICH) // http://b.android.com/213630
@RequiresApi (Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@UiThread
public static <View the extends T, V> Apply void (@NonNull T [ ] array, @ nonNull Property <? super T, V> setter, V value)
 
parameter Description:
All functions are in fact around three types of parameters:

1: View type is a generic type or subclass of a generic array or a generic collection, the parameters can be regarded as the type of binding of View 
2: Action type of interface and the type of interface Setter

public interface Action<T extends View> {
    /** Apply the action on the {@code view} which is at {@code index} in the list.*/
        @UiThread
        void apply(@NonNull T view, int index);
  }

/ ** A CAN Apply the setter that value A to A List of views. * /
Public interface Setter <View the extends T, V> {
    / ** The {@code the Set The value {ON}} Which IS AT View @code { the index in List} @code * /.
    @UiThread
     void SET (@NonNull view T, V value, int index);
  }
 
in fact, the interface Action is mainly in order to Views or View management operations, and in fact the interface to view Setter or attributes or values of the operation management views

Use Case:
use a:
@ 1: Binding View
  @Bind ({R.id.first_name, R.id.middle_name, R.id.last_name})  
  List <the EditText> nameViews; 

//2:定义Action或者Setter的实现接口类型
  static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {  
  @Override public void apply(View view, int index) {  
    view.setEnabled(false);  
  }  
};  
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {  
  @Override public void set(View view, Boolean value, int index) {  
    view.setEnabled(value);  
  }  
};

@ 3: The views invoked apply, modify views each view type attribute
ButterKnife.apply (nameViews, the DISABLE);  
ButterKnife.apply (nameViews, the ENABLED, to false);

Use way:
    for the system properties may be directly related to the system default attribute constant setting
    ButterKnife.apply (nameViews, View.ALPHA, 0.0f) ;

obfuscation embodiment
-keep class butterknife ** {*;}.  
-Dontwarn butterknife. . ** Internal  
-keep $$ ViewBinder {class ** *;}  

-keepclasseswithmembernames class * {  
    @butterknife.* <fields>;  
}  

* {class -keepclasseswithmembernames  
    @ butterknife * <Methods>;.  


The above is about the 
use of ButterKnife, if it helps you learn, then, followers point spread. This binding mechanism for follow-up analysis of the source code from the perspective of
the original link: https: //blog.csdn.net/qq_29924041/article/details/80538360

Published 49 original articles · won praise 2 · Views 8619

Guess you like

Origin blog.csdn.net/yangjunjin/article/details/99637612