Butter Knife的使用

来源:互联网 发布:heinonline数据库 编辑:程序博客网 时间:2024/05/16 17:59

转自:http://blog.csdn.net/lukejunandroid/article/details/26462807

介绍:注释字段用@ InjectView和view id找到在布局视图的ID并自动施放相应的视图,

我们经常在开发中需要写如下代码:

    class ExampleActivity extends Activity {        TextView title;        TextView subtitle;        TextView footer;              @Override public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.simple_activity);          title = (TextView) findViewById(R.id.title);          subtitle = (TextView) findViewById(R.id.subtitle);          footer = (TextView) findViewById(R.id.footer);                // TODO Use views...        }      }  

如果view非常多,我们需要写很多findById的代码,很烦,于是便可以用如下代码代替:


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

这样就大大的简化了代码,有木有?但是这段代码直接运行是会报错的,需要在Eclipse中做下配置:

1、右键单击的项目,选择Properties菜单,然后操作如图:


2、展开Annotation Processing,选择Factory Path路径,勾选"Enable project specific settings" 然后单击 "Add JARs…". 导航到项目的 libs文件夹然后选择 Butter Knife jar,如下图:


3、点击“ok”保存新的设置。 Eclipse将询问您是否要重建你的项目,你应该点击“是”。

4、确保.apt_generated/文件夹是在你的项目的根。它应该包含像YOURACTIVITY$$ ViewInjector.java文件,如果这些文件不存在触发一个干净的构建者选择的项目→clean,该文件夹及文件不应该签入到版本控制。


0 0