Android learning notes-ButterKnife 8.0 annotation usage introduction, androidbutterknife

Source: Internet
Author: User

Android learning notes-ButterKnife 8.0 annotation usage introduction, androidbutterknife
Preface:

Most App project development is based on UI pages. At this time, we need to call a large number of findViewById and setOnClickListener codes. When there are few controls, we can accept them, when there are multiple widgets, sometimes there is an impulse to smash the keyboard. So at this time, we thought we could use annotations to get rid of this heavy workload, and make the code more concise and easy to maintain, today, I will focus on the View, Resource, and Action annotation framework ButterKnife.

ButterKnife Introduction

ButterKnife is a View, Resource, and Action injection framework that focuses on the Android system.

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

GitHub: https://github.com/JakeWharton/butterknife/

Comparison before and after ButterKnife:

See how we did it before using the View annotation.

1.) before use
public class ExampleActivity extends AppCompatActivity {    private final static String TAG = ExampleActivity.class.getSimpleName();    String butterKnifeStr;    Drawable butterKnifeDrawable;    Button butterKnifeBtn;    ImageView butterKnifeIv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_butter_knife);        initResource();        initViews();    }    private void initViews() {        butterKnifeBtn = (Button) findViewById(R.id.btn_butter_knife);        butterKnifeBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Log.e(TAG, "onButterKnifeBtnClick");            }        });        butterKnifeIv = (ImageView) findViewById(R.id.iv_butter_knife);        butterKnifeBtn.setText(butterKnifeStr);        butterKnifeIv.setImageDrawable(butterKnifeDrawable);    }    private void initResource() {        butterKnifeStr = getString(R.string.title_btn_butter_knife);        butterKnifeDrawable = getDrawable(R.mipmap.ic_launcher);    }}

 

2) After use
public class ButterKnifeActivity extends AppCompatActivity {    private final static String TAG = ButterKnifeActivity.class.getSimpleName();    private Unbinder 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;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_butter_knife);        unbinder = ButterKnife.bind(this);        initViews();    }    private void initViews() {        butterKnifeBtn.setText(butterKnifeStr);        butterKnifeIv.setImageDrawable(butterKnifeDrawable);    }    @OnClick(R.id.btn_butter_knife)    public void onButterKnifeBtnClick(View view) {        Log.e(TAG, "onButterKnifeBtnClick");    }    @Override    protected void onDestroy() {        super.onDestroy();        unbinder.unbind();    }}

 

3 .) ButterKnife advantages

Analyze the advantages of ButterKnife through the comparison before and after use

  • Powerful View binding and Click event processing functions to simplify code and improve development efficiency
  • Convenient handling of ViewHolder binding in the Adapter
  • The APP efficiency is not affected during running, and configuration is convenient.
  • Code is clear and readable

Is it easy to use after comparison. Next, let's take a look at how to use it?

How to Use ButterKnife: 1.) Add the following configuration in build. gradle of the Project:
buildscript {  repositories {    mavenCentral()   }  dependencies {    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'  }}

 

2) Add the following configuration in Module build. gradle.
apply plugin: 'com.neenbedankt.android-apt'android {  ...}dependencies {  compile 'com.jakewharton:butterknife:8.1.0'  apt 'com.jakewharton:butterknife-compiler:8.1.0'}

 

3.) injection and reset Injection

Activity

class ExampleActivity extends Activity {  @BindView(R.id.title) TextView title;  @BindView(R.id.subtitle) TextView subtitle;  @BindView(R.id.footer) TextView footer;  @Override public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.simple_activity);    ButterKnife.bind(this);    // TODO Use fields...  }}

 

Fragment: Because of different view lifecycles, you need to go to onCreateView bind and onDestroyView unbind.

public class FancyFragment extends Fragment {  @BindView(R.id.button1) Button button1;  @BindView(R.id.button2) Button button2;  private Unbinder unbinder;  @Override public View 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...    return view;  }  @Override public void onDestroyView() {    super.onDestroyView();    unbinder.unbind();  }}

 

ViewHolder

public class MyAdapter 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.whatever, parent, false);      holder = new ViewHolder(view);      view.setTag(holder);    }    holder.name.setText("John Doe");    // etc...    return view;  }  static class ViewHolder {    @BindView(R.id.title) TextView name;    @BindView(R.id.job_title) TextView jobTitle;    public ViewHolder(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 annotation using @ BindDrawable (R. mipmap. ic_launcher) Drawable butterKnifeDrawable; // use @ BindBitmap (R. mipmap. ic_launcher) Bitmap butterKnifeBitmap; // Bitmap annotation using @ BindArray (R. array. day_of_week) String weeks []; // array @ BindColor (R. color. colorPrimary) int colorPrimary; // color annotation using @ BindDimen (R. dimen. activity_horizontal_margin) Float spacer;

 

6. Single Event Injection

A control specifies an Event Callback.

/***** With parameters */@ OnClick (R. id. btn_butter_knife) public void onButterKnifeBtnClick () {}/ *** with parameter */@ OnClick (R. id. btn_butter_knife) public void onButterKnifeBtnClick (View view) {Log. e (TAG, "onButterKnifeBtnClick");}/*** with parameter * @ param button */@ OnClick (R. id. btn_butter_knife) public void onButterKnifeBtnClick (Button button) {Log. e (TAG, "onButterKnifeBtnClick ");}

 

You can also specify an Event Callback using multiple controls.

/*** Two different buttons correspond to onButterKnifeBtnClick event callbacks ** @ param button */@ OnClick ({R. id. btn_butter_knife, R. id. btn_butter_knife1}) public void onButterKnifeBtnClick (Button button) {Log. e (TAG, "onButterKnifeBtnClick ");}

 

Custom controls can be bound to their own events without passing the ID.

public class FancyButton extends Button {  @OnClick  public void onClick() {    // TODO do something!  }}

 

7.) Multi-Event Callback

Listener with some views has multiple callback methods, such as adding addTextChangedListener to EditText.

editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {            }            @Override            public void afterTextChanged(Editable s) {            }        });

 

You can change the annotation Method to the following:

 @OnTextChanged(value = R.id.nameEditText, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)    void beforeTextChanged(CharSequence s, int start, int count, int after) {    }    @OnTextChanged(value = R.id.nameEditText, callback = OnTextChanged.Callback.TEXT_CHANGED)    void onTextChanged(CharSequence s, int start, int before, int count) {    }    @OnTextChanged(value = R.id.nameEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)    void afterTextChanged(Editable s) {    }

 

8 .) Selective Injection

By default ,@BindAnd listener injection are required. If the target view is not found, an error is reported. to suppress this behavior, @ Optional annotation can be used to mark the field and method, so that the injection becomes selective. If targetView exists, it is injected and does not exist, and nothing is done. or use Android's "support-annotations" library. @ Nullable in

@Nullable @BindView(R.id.might_not_be_there)TextView mightNotBeThere;@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {  // TODO ...}

 

9.) ButterKnife. apply () function

You can use the ButterKnifeapply () function to modify the view set elements or the actions, Setter, and Property of a single view.

ButterKnife.apply(nameViews, DISABLE);ButterKnife.apply(nameViews, ENABLED, false);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);  }};ButterKnife.apply(nameViews, View.ALPHA, 0.0f);

 

10.) ButterKnife. findById ()

ButterKnife also provides the findById function. You can use findById () to obtain the View in the Activity, Dialog, and view. It is a generic type and does not need to be converted.

View view = LayoutInflater.from(context).inflate(R.layout.thing, null);TextView firstName = ButterKnife.findById(view, R.id.first_name);TextView lastName = ButterKnife.findById(view, R.id.last_name);ImageView photo = ButterKnife.findById(view, R.id.photo);

 

ButterKnife automatically generates plug-in installation:

Go to AndroidStudio-> File-> Settings-> Plugins-> Search for Zelezny to download and add it. You can quickly generate instance objects for corresponding components without manual writing. In use, right-click the layout resource code of the Activity, Fragment or ViewHolder to which the annotation is to be imported, choose --> Generate -- Generate ButterKnife Injections, and then select the box that appears.

Plug-in gitHub address: https://github.com/avast/android-butterknife-zelezny

The following is a flowchart

 

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

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

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.