一把好用的黄油刀——Butter Knife

article/2025/10/21 17:40:16

一把好用的黄油刀——Butter Knife

下载JAR包之后需要进行简单的Eclipse配置
这里写图片描述
这里写图片描述

Introduction(官方简介,稍后译)

Annotate fields with @BindView and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout.

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...}
}

Instead of slow reflection, code is generated to perform the view look-ups. Calling bind delegates to this generated code that you can see and debug.

The generated code for the above example is roughly equivalent to the following:

public void bind(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);
}

Resource Binding

Bind pre-defined resources with @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString, which binds an R.bool ID (or your specified type) to its corresponding field.

class ExampleActivity extends Activity {@BindString(R.string.title) String title;@BindDrawable(R.drawable.graphic) Drawable graphic;@BindColor(R.color.red) int red; // int or ColorStateList field@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field// ...
}

Non-Activity Binding

You can also perform binding on arbitrary objects by supplying your own view root.

public class FancyFragment extends Fragment {@BindView(R.id.button1) Button button1;@BindView(R.id.button2) Button button2;@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fancy_fragment, container, false);ButterKnife.bind(this, view);// TODO Use fields...return view;}
}

Another use is simplifying the view holder pattern inside of a 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 {@BindView(R.id.title) TextView name;@BindView(R.id.job_title) TextView jobTitle;public ViewHolder(View view) {ButterKnife.bind(this, view);}}
}

You can see this implementation in action in the provided sample.

Calls to ButterKnife.bind can be made anywhere you would otherwise put findViewById calls.

Other provided binding APIs:

Bind arbitrary objects using an activity as the view root. If you use a pattern like MVC you can bind the controller using its activity with ButterKnife.bind(this, activity).
Bind a view's children into fields using ButterKnife.bind(this). If you use <merge> tags in a layout and inflate in a custom view constructor you can call this immediately after. Alternatively, custom view types inflated from XML can use it in the onFinishInflate() callback.

View Lists

You can group multiple views into a List or array.

@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;The apply method allows you to act on all the views in a list at once.ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);

Action and Setter interfaces allow specifying 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);}
};

An Android Property can also be used with the apply method.

ButterKnife.apply(nameViews, View.ALPHA, 0.0f);

Listener Binding

Listeners can also automatically be configured onto methods.

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

All arguments to the listener method are optional.

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

Define a specific type and it will automatically be cast.

@OnClick(R.id.submit)
public void sayHi(Button button) {button.setText("Hello!");
}

Specify multiple IDs in a single binding for common event handling.

@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();}
}

Custom views can bind to their own listeners by not specifying an ID.

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

Binding Reset

Fragments have a different view lifecycle than activities. When binding a fragment in onCreateView, set the views to null in onDestroyView. Butter Knife returns an Unbinder instance when you call bind to do this for you. Call its unbind method in the appropriate lifecycle callback.

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

Optional Bindings

By default, both @Bind and listener bindings are required. An exception will be thrown if the target view cannot be found.

To suppress this behavior and create an optional binding, add a @Nullable annotation to fields or the @Optional annotation to methods.

Note: Any annotation named @Nullable can be used for fields. It is encouraged to use the @Nullable annotation from Android’s “support-annotations” library.

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

Multi-Method Listeners

Method annotations whose corresponding listener has multiple callbacks can be used to bind to any one of them. Each annotation has a default callback that it binds to. Specify an alternate using 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 ...
}

Bonus

Also included are findById methods which simplify code that still has to find views on a View, Activity, or Dialog. It uses generics to infer the return type and automatically performs the cast.

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

Add a static import for ButterKnife.findById and enjoy even more fun.
Download
Gradle

compile 'com.jakewharton:butterknife:(insert latest version)'
apt 'com.jakewharton:butterknife-compiler:(insert latest version)'

http://chatgpt.dhexx.cn/article/2JNJ4mDg.shtml

相关文章

Android神兵利器之黄油刀的使用(ButterKnife)

黄油刀的使用是非常简单的事情&#xff0c;下载的时候需要注意的有两步&#xff1a; 1.下载jar&#xff0c;而下载jar包则有两种方法&#xff1a; A&#xff1a; File->Project Structure->Dependencies->Library dependency 中直接搜索butterknife选择任意一个就可…

android[butterKnife(黄油刀)史诗详细使用方法]

butterKnife中文又名黄油刀&#xff0c;是一款Android视图的字段和方法绑定快速注解框架。 1.首先把查看方式改变成Android。 2.打开Gradle Scripts层下的build.radle注意括号内是module的文件。 3.将代码粘贴到如下位置。 implementation com.jakewharton:butterknife:10.2.3…

butterknife----黄油刀

Butter Knife&#xff0c;专门为Android View设计的绑定注解&#xff0c;专业解决各种findViewById。 简单使用&#xff1a; 添加依赖&#xff1a; Download dependencies { compile com.jakewharton:butterknife:8.8.1 annotationProcessor com.jakewharton:butterknife-com…

黄油刀使用方法(butterknife)

使用心得&#xff1a; 1.Activity ButterKnife.bind(this);必须在setContentView();之后&#xff0c;且父类bind绑定后&#xff0c;子类不需要再bind 2.Fragment ButterKnife.bind(this, mRootView); 3.属性布局不能用private or static 修饰&#xff0c;否则会报错 4.setConte…

Android:butterKnife(黄油刀的简单使用

butterKnife中文又名黄油刀&#xff0c;是一款Android视图的字段和方法绑定快速注解。 1.1首先把查看方式改变成Android。 implementation com.jakewharton:butterknife:10.2.3// 添加此依赖 annotationProcessor com.jakewharton:butterknife-compiler:10.2.3// 添加此规…

Android中ButterKnife(黄油刀)的详细使用

最近刚学会使用ButterKnife&#xff0c;真是超级好用&#xff0c;忍不住要分享给大家了。 写在前面&#xff1a;该文档使用7.0版本&#xff0c;8.0版本方法名有所改动&#xff0c;建议看官方文档&#xff0c;整体业务逻辑和原理没什么变动。 在android编程过程中&#xff0c;我…

黄油刀

【攻克Android (34)】Butter Knife 黄油刀 博客分类&#xff1a; 攻克Android系列 本文围绕以下四个部分展开&#xff1a; 一、注解式框架 二、Butter Knife 案例一 案例二&#xff1a;用 ListView 展示一个列表数据&#xff0c;每个Item里含有一个Button&#xff0c;可以…

ButterKnife黄油刀

ButterKnife黄油刀 1、强大的View绑定和Click事件处理功能&#xff0c;简化代码&#xff0c;提升开发效率 2、方便的处理Adapter里的ViewHolder绑定问题 3、运行时不会影响APP效率&#xff0c;使用配置方便 4、代码清晰&#xff0c;可读性强 怎么配置 在android Studio项…

Android版黄油刀简介

Butter Knife? 黄油刀是一个非常好的Android视图注入库。 黄油刀有助于减少许多样板代码&#xff08;例如&#xff0c;重复的findViewById调用&#xff09;。 如果您处理的活动具有大量的视图&#xff0c;那么您就会知道&#xff0c;将代码与“ findViewById”集群在一起时&a…

Android(ButterKnife)黄油刀使用详解

一、什么是ButterKnife黄油刀&#xff1f; 1.1ButterKnife中文又名黄油刀&#xff0c;是一款Android视图的字段和方法绑定快速注解框架。 1.2使用方法&#xff1a; 1.打开budild.gradle 文件 2.在dependencies 中添加 implementation com.jakewharton:butterknife:10.2.3// …

Android Butterknife(黄油刀) 使用方法总结

转载请标明出处&#xff1a;http://blog.csdn.net/donkor_/article/details/77879630 前言&#xff1a; ButterKnife是一个专注于Android系统的View注入框架,以前总是要写很多findViewById来找到View对象&#xff0c;有了ButterKnife可以很轻松的省去这些步骤。是大神JakeWha…

ArrayList$SubList.add导致的java.lang.StackOverflowError : null :慎用subList

项目场景&#xff1a; 上线后遇到的1个StackOverflowError问题&#xff0c;这里做个分析。通过日志文件可以看到&#xff1a; java.lang.StackOverflowError: nullat java.util.ArrayList$SubList.add(ArrayList.java:1047)at java.util.ArrayList$SubList.add(ArrayList.jav…

ArrayList和SubList的坑面试题

&#x1f468;&#x1f3fb;‍&#x1f393;博主介绍&#xff1a;大家好&#xff0c;我是芝士味的椒盐&#xff0c;一名在校大学生&#xff0c;热爱分享知识&#xff0c;很高兴在这里认识大家&#x1f31f; &#x1f308;擅长领域&#xff1a;Java、大数据、运维、电子 &#x…

NetSuite Sublist解释

今朝汇编一下Sublist主题的知识点以备忘。 2个数据源类型 Related Record - 以Saved Search建立的关联记录&#xff1b;Child Record - 父子表&#xff1b; 1. Related Record Saved Search关键点 这种形式的Sublist是利用Saved Search作为Sublist的数据源&#xff0c;将某…

各位,请慎用 subList!原来这么多坑!!

点击关注公众号&#xff0c;Java干货及时送达 1. 使用Arrays.asList的注意事项 1.1 可能会踩的坑 先来看下Arrays.asList的使用&#xff1a; List<Integer> statusList Arrays.asList(1, 2); System.out.println(statusList); System.out.println(statusList.contains(1…

Java中List的subList()方法及使用注意事项

List<Object> list new Arraylist<>();List<Object> subList list.subList(0, 5);其中subList(0, 5)取得的是下标为0到4的元素,不包含下标为5的元素. java.util.List中的subList方法返回列表中指定的 fromIndex&#xff08;包括 &#xff09;和 toIndex&a…

Java 中 List.subList() 方法的使用陷阱

转载请注明本文出自 clevergump 的博客&#xff1a;http://blog.csdn.net/clevergump/article/details/51105235, 谢谢! 前言 本文原先发表在我的 iteye博客: http://clevergump.iteye.com/admin/blogs/2211979, 但由于在 iteye发表的这篇文章的某些渲染曾经出现过一些问题, 我…

【Java】List的subList方法

Java的容器类ArrayList很常用&#xff0c;旗下存在一个subList方法&#xff0c;是值得注意的。 subList方法仅能够取出此ArrayList的引用&#xff0c;即使其看起来&#xff0c;好像是取出一个ArrayList的子ArrayList。 其实不然&#xff0c;subList方法的返回值&#xff0c;只是…

Java中的subList方法

Java中的subList方法 今天看到了java中List中有个subList的方法&#xff0c;感觉很熟悉有没有&#xff1f;没错&#xff0c;在Stirng类中&#xff0c;也有个类似的方法&#xff1a;subString。 Stirng中的subString方法&#xff0c;官方解释是&#xff1a;返回字符串的子字符串…

Java中List集合的subList方法

目录 一、说明 二、测试 1、直接输出 2、向subList中添加元素再输出 3、 从subList中删除元素再输出 4、向list中添加元素再输出 5、从list中删除一个元素后再输出 ​ 6、向list中添加元素&#xff0c;输出list&#xff0c;然后将subList传入ArrayList生成新集合在输出…