转载出处:http://blog.youkuaiyun.com/zjbpku/article/details/18676149
Butter Knife也是使用注入视图的方式使开发人员尽可能少的编写代码。相比AndroidAnnotations,个人觉得没有AndroidAnnotations
使用简单,而且文档几乎也没有。还是先看一小段代码吧:
package com.example.butterknife;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.ButterKnife;
import butterknife.OnItemClick;
import butterknife.OnLongClick;
import static android.widget.Toast.LENGTH_SHORT;
public class SimpleActivity extends Activity {
@InjectView(R.id.title) TextView title;
@InjectView(R.id.subtitle) TextView subtitle;
@InjectView(R.id.hello) Button hello;
@InjectView(R.id.list_of_things) ListView listOfThings;
@InjectView(R.id.footer) TextView footer;
private SimpleAdapter adapter;
@OnClick(R.id.hello) void sayHello() {
Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
}
@OnLongClick(R.id.hello) boolean sayGetOffMe() {
Toast.makeText(this, "Let go of me!", LENGTH_SHORT).show();
return true;
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// Contrived code to use the "injected" views.
title.setText("Butter Knife");
subtitle.setText("View \"injection\" for Android.");
footer.setText("by Jake Wharton");
hello.setText("Say Hello");
}
}
总之,两者虽有相似的地方,但看到AndroidAnnotations之后,就不愿使用Butter Knife了。另外,值得你注意的是butter Knife
有个代码生成的插件呢,不过是针对Android Studio的,请看图:
- 插件使用:
- 在所使用的布局 ID 上点击右键 (例如上图中的 R.layout.activity_settings ),
- 然后选择
Generate
->Generate ButterKnife Injections
- 在对话框中选择需要注入的 View, 还有个选项可以给 Adapter 创建一个 ViewHolder。
-
点击 Confirm
, 代码自动生成!
插件项目主页:
https://github.com/inmite/android-butterknife-zelezny
下载插件:
http://plugins.jetbrains.com/plugin/7369