android懒人工具Butter Knife!黄油刀!8.2.1

Butter Knife!

准备工作

1在项目级的build.gradle中在文件顶部加入(不然会提示找不到apt())

apply plugin: 'android-apt'

并且在文件内容中加入下面两行

dependencies {   
  ....
  compile 'com.jakewharton:butterknife:8.2.1'  
  apt 'com.jakewharton:butterknife-compiler:8.2.1'
}

2在工程级的build.gradle文件中加入

dependencies {  
  classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'   
 ...
}

3在oncreate中加入以下代码注册工具

@Override //在activity中
public void onCreate(Bundle savedInstanceState) {    
   super.onCreate(savedInstanceState);       
   setContentView(R.layout.simple_activity); 
   ButterKnife.bind(this); //使用该语句注册
}
@Override //在fragment中
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;
}

@BindView 代替这findViewById的方法 ,该方法相当于修饰了private static

@BindView(R.id.title) TextView title; 
@BindView(R.id.subtitle) TextView subtitle; 
@BindView(R.id.footer) TextView footer;

同样的,当我们需要使用图片、字符串等资源的时候

@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

官方网站:http://jakewharton.github.io/butterknife/

你可能感兴趣的:(android懒人工具Butter Knife!黄油刀!8.2.1)