Android View Injection Library: Butterknife

Source: Internet
Author: User

Introduction
Butterknife is found and automatically converted to the corresponding layout view on your layout through the variables of the @injectview and view ID annotations.

Class Exampleactivity extends Activity {
@InjectView (r.id.title) TextView title;
@InjectView (r.id.subtitle) TextView subtitle;
@InjectView (r.id.footer) TextView footer;

@Override public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.simple_activity);
Butterknife.inject (this);
TODO use "injected" views ...
}
}


Unlike the slow reflection mechanism, the resulting code is a look-up (lookup view) operation used to perform the view. The code generated by calling the inject method can be viewed and debugged. The code in the example above can be roughly equivalent to the following:

public void inject (exampleactivity activity) {
Activity.subtitle = (Android.widget.TextView) Activity.findviewbyid (2130968578);
Activity.footer = (Android.widget.TextView) Activity.findviewbyid (2130968579);
Activity.title = (Android.widget.TextView) Activity.findviewbyid (2130968577);
}


non-activity injection
You can also provide your own root view to perform injection on arbitrary objects:

public class Fancyfragment extends Fragment {
@InjectView (R.id.button1) Button button1;
@InjectView (R.id.button2) Button button2;

@Override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
View view = Inflater.inflate (R.layout.fancy_fragment, container, false);
Butterknife.inject (this, view);
TODO use "injected" views ...
return view;
}
}


Another usage is to simplify the Viewholder mode in the list adapter:

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 {
@InjectView (r.id.title) TextView name;
@InjectView (r.id.job_title) TextView jobtitle;

Public Viewholder (view view) {
Butterknife.inject (this, view);
}
}
}


You can see the implementation of its behavior in the example above. You can use Butterknife.inject wherever you can use the Findviewbyid.
Additional injection APIs provided:
You can use activity as the root view to inject arbitrary objects. If you use an MVC-like architecture, you can inject it by using butterknife.inject (this, activity) in the activity of the controller (C).
You can use Butterknife.inject (this) to inject a child view. If you use the <merge> tag in the layout and load the custom control, you can call it immediately later. Or, you can use it in the Onfinishinflate () callback by using a custom view loaded in XML.

View Columns
You can centralize multiple views into a list or array.

@InjectViews ({r.id.first_name, r.id.middle_name, r.id.last_name})
List<edittext> nameviews;


The Apply method can perform the behavior of all views in the list at once:

Butterknife.apply (Nameviews, DISABLE);
Butterknife.apply (Nameviews, ENABLED, false);
The action and setter interfaces allow you to define simple behavior:

Static final action<view> DISABLE = new Action<> () {
@Override public void Apply (view view, int index) {
View.setenabled (FALSE);
}
}
Static final Setter<view, boolean> ENABLED = new Setter<> () {
@Override public void Set (view view, Boolean value, int index) {
view.setenabled (value);
}
}

Android's own properties can also be used with the Apply method.

Butterknife.apply (nameviews, View.alpha, 0);

Tap Listen injection
Clicking on the listener can also be automatically set to the method.

@OnClick (R.id.submit)
public void Submit () {
TODO submit data to server ...
}


You can pass the view as a parameter into the method. Declares a specified type

@OnClick (R.id.submit)
public void Sayhi (Button button) {
Button.settext ("hello!");
}


Declare multiple IDs for the same event action in one binding.

@OnClick ({r.id.door1, R.id.door2, R.id.door3})
public void Pickdoor (Doorview door) {
if (Door.hasprizebehind ()) {
Toast.maketext (This, "You win!", Length_short). Show ();
} else {
Toast.maketext (This, "Try again", Length_short). Show ();
}
}


Injection Reset
Fragment has a more different declaration cycle than activity, and when injected in fragment Oncreateview, the view should be set to empty in the Ondestroyview. Butterknife has a reset method that can do this automatically.

public class Fancyfragment extends Fragment {
@InjectView (R.id.button1) Button button1;
@InjectView (R.id.button2) Button button2;

@Override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
View view = Inflater.inflate (R.layout.fancy_fragment, container, false);
Butterknife.inject (this, view);
TODO use "injected" views ...
return view;
}

@Override void Ondestroyview () {
Super.ondestroyview ();
Butterknife.reset (this);
}
}


Optional Injection
By default, @InjectView and @onclick are required (this must be the case in the following sentence). Throws an exception if the target view is not found. To prohibit the appearance of this behavior and create an optional injection, add the @optional annotation to the value or method.

@Optional @InjectView (r.id.might_not_be_there) TextView mightnotbethere;

@Optional @OnClick (r.id.maybe_missing) void onmaybemissingclicked () {
Todo...
}


Multiple callback monitoring
The corresponding listener annotations with multiple callbacks can be used to bind any one of them. Each annotation has its corresponding default callback. Specifies that any one use the callback parameter.


@OnItemSelected (R.id.list_view)
void onitemselected (int position) {
Todo...
}

@OnItemSelected (value = r.id.maybe_missing, callback = nothing_selected)
void onnothingselected () {
Todo...
}


Additional Rewards
The FindByID method that contains the two simplified code still needs to be found in view or activity. It uses generics to infer the return type and perform the conversion automatically.

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);


Adding static introductions to Butterknife.findbyid is more interesting.Introduction
Butterknife is found and automatically converted to the corresponding layout view on your layout through the variables of the @injectview and view ID annotations.

Class Exampleactivity extends Activity {
@InjectView (r.id.title) TextView title;
@InjectView (r.id.subtitle) TextView subtitle;
@InjectView (r.id.footer) TextView footer;

@Override public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.simple_activity);
Butterknife.inject (this);
TODO use "injected" views ...
}
}


Unlike the slow reflection mechanism, the resulting code is a look-up (lookup view) operation used to perform the view. The code generated by calling the inject method can be viewed and debugged. The code in the example above can be roughly equivalent to the following:

public void inject (exampleactivity activity) {
Activity.subtitle = (Android.widget.TextView) Activity.findviewbyid (2130968578);
Activity.footer = (Android.widget.TextView) Activity.findviewbyid (2130968579);
Activity.title = (Android.widget.TextView) Activity.findviewbyid (2130968577);
}


non-activity injection
You can also provide your own root view to perform injection on arbitrary objects:

public class Fancyfragment extends Fragment {
@InjectView (R.id.button1) Button button1;
@InjectView (R.id.button2) Button button2;

@Override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
View view = Inflater.inflate (R.layout.fancy_fragment, container, false);
Butterknife.inject (this, view);
TODO use "injected" views ...
return view;
}
}


Another usage is to simplify the Viewholder mode in the list adapter:

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 {
@InjectView (r.id.title) TextView name;
@InjectView (r.id.job_title) TextView jobtitle;

Public Viewholder (view view) {
Butterknife.inject (this, view);
}
}
}


You can see the implementation of its behavior in the example above. You can use Butterknife.inject wherever you can use the Findviewbyid.
Additional injection APIs provided:
You can use activity as the root view to inject arbitrary objects. If you use an MVC-like architecture, you can inject it by using butterknife.inject (this, activity) in the activity of the controller (C).
You can use Butterknife.inject (this) to inject a child view. If you use the <merge> tag in the layout and load the custom control, you can call it immediately later. Or, you can use it in the Onfinishinflate () callback by using a custom view loaded in XML.

View Columns
You can centralize multiple views into a list or array.

@InjectViews ({r.id.first_name, r.id.middle_name, r.id.last_name})
List<edittext> nameviews;


The Apply method can perform the behavior of all views in the list at once:

Butterknife.apply (Nameviews, DISABLE);
Butterknife.apply (Nameviews, ENABLED, false);
The action and setter interfaces allow you to define simple behavior:

Static final action<view> DISABLE = new Action<> () {
@Override public void Apply (view view, int index) {
View.setenabled (FALSE);
}
}
Static final Setter<view, boolean> ENABLED = new Setter<> () {
@Override public void Set (view view, Boolean value, int index) {
view.setenabled (value);
}
}

Android's own properties can also be used with the Apply method.

Butterknife.apply (nameviews, View.alpha, 0);

Tap Listen injection
Clicking on the listener can also be automatically set to the method.

@OnClick (R.id.submit)
public void Submit () {
TODO submit data to server ...
}


You can pass the view as a parameter into the method. Declares a specified type

@OnClick (R.id.submit)
public void Sayhi (Button button) {
Button.settext ("hello!");
}


Declare multiple IDs for the same event action in one binding.

@OnClick ({r.id.door1, R.id.door2, R.id.door3})
public void Pickdoor (Doorview door) {
if (Door.hasprizebehind ()) {
Toast.maketext (This, "You win!", Length_short). Show ();
} else {
Toast.maketext (This, "Try again", Length_short). Show ();
}
}


Injection Reset
Fragment has a more different declaration cycle than activity, and when injected in fragment Oncreateview, the view should be set to empty in the Ondestroyview. Butterknife has a reset method that can do this automatically.

public class Fancyfragment extends Fragment {
@InjectView (R.id.button1) Button button1;
@InjectView (R.id.button2) Button button2;

@Override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {
View view = Inflater.inflate (R.layout.fancy_fragment, container, false);
Butterknife.inject (this, view);
TODO use "injected" views ...
return view;
}

@Override void Ondestroyview () {
Super.ondestroyview ();
Butterknife.reset (this);
}
}


Optional Injection
By default, @InjectView and @onclick are required (this must be the case in the following sentence). Throws an exception if the target view is not found. To prohibit the appearance of this behavior and create an optional injection, add the @optional annotation to the value or method.

@Optional @InjectView (r.id.might_not_be_there) TextView mightnotbethere;

@Optional @OnClick (r.id.maybe_missing) void onmaybemissingclicked () {
Todo...
}


Multiple callback monitoring
The corresponding listener annotations with multiple callbacks can be used to bind any one of them. Each annotation has its corresponding default callback. Specifies that any one use the callback parameter.


@OnItemSelected (R.id.list_view)
void onitemselected (int position) {
Todo...
}

@OnItemSelected (value = r.id.maybe_missing, callback = nothing_selected)
void onnothingselected () {
Todo...
}


Additional Rewards
The FindByID method that contains the two simplified code still needs to be found in view or activity. It uses generics to infer the return type and perform the conversion automatically.

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);


Adding static introductions to Butterknife.findbyid is more interesting.

Android View Injection Library: Butterknife

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.