android注解[Jake Wharton Butter Knife]
Introduction
Annotate fields with @InjectView
and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout.
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...
}
}
Instead of slow reflection, code is generated to perform the view look-ups. Calling inject
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 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 perform injection on arbitrary objects by supplying your own view root.
public class FancyFragment extends Fragment {
@InjectView(R.id.button1) Button button1;
@InjectView(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.inject(this, view);
// TODO Use "injected" views...
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 {
@InjectView(R.id.title) TextView name;
@InjectView(R.id.job_title) TextView jobTitle; public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
}
You can see this implementation in action in the provided sample.
Calls to ButterKnife.inject
can be made anywhere you would otherwise put findViewById
calls.
Other provided injection APIs:
- Inject arbitrary objects using an activity as the view root. If you use a pattern like MVC you can inject the controller using its activity with
ButterKnife.inject(this, activity)
. - Inject a view's children into fields using
ButterKnife.inject(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 theonFinishInflate()
callback.
VIEW LISTS
You can group 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 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 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);
}
}
An Android Property
can also be used with the apply
method.
ButterKnife.apply(nameViews, View.ALPHA, 0);
LISTENER INJECTION
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 {
@OnClick
public void onClick() {
// TODO do something!
}
}
INJECTION RESET
Fragments have a different view lifecycle than activities. When injecting a fragment in onCreateView
, set the views to null
in onDestroyView
. Butter Knife has a reset
method to do this automatically.
public class FancyFragment extends Fragment {
@InjectView(R.id.button1) Button button1;
@InjectView(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.inject(this, view);
// TODO Use "injected" views...
return view;
} @Override public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
}
OPTIONAL INJECTIONS
By default, both @InjectView
and listener injections are required. An exception will be thrown if the target view cannot be found.
To suppress this behavior and create an optional injection, add the @Optional
annotation to the field or method.
@Optional @InjectView(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
The source code to the library and sample application as well as this website is available on GitHub. The Javadoc is also available to browse.
MAVEN
If you are using Maven for compilation you can declare the library as a dependency.
<dependency>
<groupId>com.jakewharton</groupId>
<artifactId>butterknife</artifactId>
<version>6.1.0</version>
</dependency>
GRADLE
compile 'com.jakewharton:butterknife:6.1.0'
Be sure to supress this lint warning in your build.gradle
.
lintOptions {
disable 'InvalidPackage'
}
Some configurations may also require additional exclusions.
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
IDE CONFIGURATION
Some IDEs require additional configuration in order to enable annotation processing.
- IntelliJ IDEA — If your project uses an external configuration (like a Maven
pom.xml
) then annotation processing should just work. If not, try manual configuration. - Eclipse — Set up manual configuration.
PROGUARD
Butter Knife generates and uses classes dynamically which means that static analysis tools like ProGuard may think they are unused. In order to prevent them from being removed, explicitly mark them to be kept. To prevent ProGuard renaming classes that use @InjectView on a member field the keepclasseswithmembernames
option is used.
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewInjector { *; } -keepclasseswithmembernames class * {
@butterknife.* <fields>;
} -keepclasseswithmembernames class * {
@butterknife.* <methods>;
}
License
Copyright 2013 Jake Wharton Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
android注解[Jake Wharton Butter Knife]的更多相关文章
- Android RoboGuice开源框架、Butter Knife开源框架浅析
Google Guice on Android(RoboGuice) 今天介绍一下Google的这个开源框架RoboGuice, 它的作用跟之前讲过的Dagger框架差点儿是一样的,仅仅是Dagger ...
- Butter Knife使用详解
Butter Knife Github地址: https://github.com/JakeWharton/butterknife 官方说明给出的解释是 Bind Android views and ...
- android Butter Knife 使用详解
Butter Knife github连接:https://github.com/JakeWharton/butterknife 本文使用的butterknife版本7.0.1 butterknife ...
- Android Studio & Butter Knife —— 快速开发
Butter Knife是一个Android的注解框架,可以帮助用户快速完成视图.资源与对象的绑定,完成事件的监听.(也就是少写findViewById()) 具体的介绍可以参考官方主页: http: ...
- Android:Butter Knife 8.0.1配置
github地址:https://github.com/GarsonZhang/butterknife Butter Knife Field and method binding for Androi ...
- [轉]Android Libraries 介紹 - Butter knife
原文地址 Butter Knife 簡介 Butter Knife - Field and method binding for Android views.助你簡化程式碼,方便閱讀. 使用方法 開發 ...
- Android 注解工具 ButterKnife
Butter Knife 是 Android 视图字段和方法绑定,使用注解处理来生成样板代码. 主要特性: 在字段使用 @FindView消除findViewById调用 使用 @FindViews在 ...
- Butter Knife 黄油刀
简介 Github:https://github.com/JakeWharton/butterknife 文档 特点: 采用注解的方式实现强大的View绑定和Click事件处理功能,简化代码,提升开 ...
- Butter Knife:一个安卓视图注入框架
Butter Knife:一个安卓视图注入框架 2014年5月8日 星期四 14:52 官网: http://jakewharton.github.io/butterknife/ GitHub地址: ...
随机推荐
- 玩转变量、环境变量以及数学运算(shell)
变量和环境变量 var=value 给变量赋值,输出语句:$ echo $var或者是$ echo ${var},记住中间有个空格 例如:name="coffee" age ...
- PHP安装环境,服务器不支持curl_exec的解决办法
转自:http://jingyan.baidu.com/article/00a07f38909c6b82d028dc83.html windows下开启方法: 拷贝PHP目录中的libeay32.dl ...
- jquery下拉框实现将左边的选项添加到右边区域
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- props 和 state的区别
作者:孙志勇 微博 日期:2016年11月29日 一.时效性 所有信息都具有时效性.文章的价值,往往跟时间有很大关联.特别是技术类文章,请注意本文创建时间,如果本文过于久远,请读者酌情考量,莫要浪费时 ...
- android手机ping不通linux的ip地址
我的linux是装载虚拟机里的,修改虚拟机的网络连接方式为桥接模式即可.
- SCROLLINFO结构体中fMask和nPage的理解
还是VC++中有关显示图像的问题. 我们在显示一幅比较大的图像时,要使用带标准滚动条的对话框.涉及对滚动条的操作就不得不提SCROLLINFO这个结构体.只看单词意思就这道这个结构体要储存滚动条的一些 ...
- head first-----------adpter pattern
head first-----------------深入浅出适配器模式 适配器模式:将一个类的接口,转换成客户想要的另外一个接口,适配器然原本接口不兼容的类可以合作无间.从而可以不用更改旧 ...
- 让AllocateHwnd接受一般函数地址作参数
http://www.xuebuyuan.com/1889769.html Classes单元的AllocateHWnd函数是需要传入一个处理消息的类的方法的作为参数的,原型: function Al ...
- C# 多线程处理相关说明: WaitHandle,waitCallback, ThreadPool.QueueUserWorkItem
class TestThread { static void Main() { //使用WaitHandle静态方法阻止一个线程,直到一个或多个同步对象接收到信号 WaitHandle[] waitH ...
- [转]使用 PIVOT 和 UNPIVOT
可以使用 PIVOT 和 UNPIVOT 关系运算符将表值表达式更改为另一个表.PIVOT 通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执 ...