How to become a T – type talent, vertical in an industry, must have a setThe knowledge systemHere, just one word insist ~

preface

ButterKnife is an IOC framework that focuses on View controls in Android, event listening injection. In addition, for performance reasons, annotations +APT compile-time parsing is used instead of radiating. When using ButterKnife for project development, it is relatively simple to use, but behind the simplicity does not mean that it is easy. Later, I will analyze the source code of ButterKnife. Thank you

Contests

How to introduce the environment

android {
  ...
  // Butterknife requires Java 8.
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}
Copy the code
  • Increasing dependencies (Java)

    Implementation 'com. Jakewharton: butterknife: 10.2.1 annotationProcessor' com. Jakewharton: butterknife - compiler: 10.2.1 'Copy the code
  • Increasing dependencies (Kotlin)

    Implementation 'com. Jakewharton: butterknife: 10.2.1 kapt' com. Jakewharton: butterknife - compiler: 10.2.1 'Copy the code

    Note: to use kapt you need to reference it in build.gradle (apply plugin: ‘kotlin-kapt’)

2. Different layout binding modes (Butterknife.bind)

2.1,ActivityAdd butterknife. bind(this) to the onCreate method.

public class MainActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Bind initializes ButterKnife Butterknife. bind(this); }}Copy the code

2.2,FragmentButterknife. bind(this, view) returns a view using the inflater inflater

public class ButterknifeFragment extends Fragment{ private Unbinder mUnbinder; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); GetActivity () mUnbinder = butterknife.bind (this, view); // Return an Unbinder value. return view; } @override public void onDestroyView() {super.onDestroyView(); if(mUnbinder! =null){ mUnbinder.unbind(); }}}Copy the code

Note: You need to unbind it

2.3,AdapterThe inner class ViewHolder needs only to be bound in the constructor call butterknife. bind(this, view)

public class ButterknifeAdapter extends BaseAdapter { @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; if (view ! = null) { holder = (ViewHolder) view.getTag(); } else { view = inflater.inflate(R.layout.testlayout, parent, false); holder = new ViewHolder(view); view.setTag(holder); } holder.title.setText("xxx"); holder.nmae.setText("xxx"); return view; } static class ViewHolder { @BindView(R2.id.title) TextView title; @BindView(R2.id.name) TextView name; public ViewHolder(View view) { ButterKnife.bind(this, view); }}}Copy the code

3. View binding unlock (@bindView)

3.1 binding of a single control

 @BindView(R2.id.first_name)
 EditText firstName;
 @BindView(R2.id.middle_name)
 EditText middleName;
 @BindView(R2.id.last_name)
 EditText lastName;
Copy the code

3.2. One-time binding of multiple controls

public class MainActivity extends AppCompatActivity { @BindViews({ R2.id.first_name, R2.id.middle_name, R2.id.last_name}) List<EditText> nameViews ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); nameViews.get( 0 ).setText( "hello 1 "); nameViews.get( 1 ).setText( "hello 2 "); nameViews.get( 2 ).setText( "hello 3 "); }}Copy the code

4, OnClick event binding unlock

4.1 OnClick and OnLongClick single click event handling

public class MainActivity extends AppCompatActivity { @OnClick(R2.id.button1) public void onViewClicked() { Toast.maketext (this, "this is the bound click event ", toast.length_short).show(); } @onLongclick (r2.id.button2) public Boolean onViewClickeds(){toast.makeText (this, "This is bound to the long press event ", Toast.LENGTH_SHORT).show(); return true ; }}Copy the code

4.2 Multi-click event processing

@OnClick({R2.id.button1, R2.id.button2}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.button1: Toast.maketext (this, "button1 click event ", toast.length_short).show(); break; Case r.i.button2: toast.maketext (this, "button2 click event ", toast.length_short).show(); break; }}Copy the code

4.3 Custom type event processing

  • OnPageSelected()
    @onPagechange (r2.id.viewpager) public void onPageSelected(int position) {switch (position) {case 0: // Slide to the first page break; Case 1: // Slide to break; }}Copy the code
  • RadioGroup+RadioButton OnCheckedChanged()
    @OnCheckedChanged({R2.id.click1,R2.id.click2}) public void OnCheckedChangeListener(CompoundButton view, boolean ischanged ){ switch (view.getId()) { case R.id.click1: If (ischanged){if (ischanged){if (ischanged){if (ischanged){if (ischanged){} break; Case rc.lick2: if (ischanged) {break; default: break; }}Copy the code
  • Other events
    annotations function
    @OnEditorAction Function keys of the soft keyboard
    @OnFocusChange Changes in focus
    @OnItemClick item Set the control attribute focusable to false if the Button or Button has clicked control events in it.
    @OnItemLongClick item Long press (return true to intercept onItemClick)
    @OnItemSelected Event that item is selected
    @OnTextChanged The text change event in EditText
    @OnPageSelected ViewPager slides to select events
    @OnCheckedChanged RadioGroup selects events

5. Resource binding unlocking

5.1 Bitmap image resource binding

@BindBitmap(R2.mipmap.icon)
Bitmap bitmap;
Copy the code

5.2 String String resource binding

@BindString(R2.string.name)  
String name;  
Copy the code

String Array resource binding

<resources> <string-array name="city"> <item> Guangzhou </item> <item> Shenzhen </item> <item> Shantou </item> </string-array> </resources> @bindarray (r2.array. city) // Bind string array array string [] citys;Copy the code

5.4 ColorResId Resource binding:

@BindColor(R2.color.white) 
int white;
Copy the code

5.5 Dimen Resource binding

@BindDimen(R2.dimen.width)
int width;
Copy the code

5.6, Drawable resource binding

@BindDrawable(R2.drawable.image) 
Drawable image;
Copy the code

6. Basic type binding unlock

6.1. Bind Int types

@BindInt(R2.int.size)
int size;
Copy the code

6.2. Bind Bool

@BindBool(R2.bool.flag)
boolean flag;
Copy the code

6.3. Bind the Float type

@BindFloat(R2.dimen.size)
float size;
Copy the code

Other usage

7.1. Use the Apply method to operate on all views in the list at once

@BindViews({ R2.id.first_name, R2.id.middle_name, R2.id.last_name }) List<EditText> nameViews; ButterKnife.apply(nameViews, DISABLE); ButterKnife.apply(nameViews, ENABLED, false); // The Action and Setter interfaces allow you to specify simple behavior. 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); }}; //Android attributes can also be used with the apply method. ButterKnife. Apply (nameViews, the ALPHA, 0.0 f);Copy the code

7.2 When a View is bound to an event, the target View cannot be found, which will cause an exception

To suppress this behavior and create Optional bindings, add an @Nullable annotation to the field or an @Optional annotation to the method.

@nullable @bindView (r2.id.title) TextView mTitle; @optional @onclick (r2.id.click) public void onViewClicked() {// TODO... }Copy the code

About me