这一系列文章,将整理Retrofit、RxJava(RxAndroid)、Dagger2、ButterKnife 等几个开源库的结合使用学习笔记,希望自己能够在Android 开发上有更大的进步。
好!现在就从ButterKnife 开始啦!
安装插件
进入Android Studio - Preferences - Plugins:
点击”Browse Repositories” 搜索ButterKnife,安装插件,重启AS即可:
Gradle 配置:
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
Activity 中的用法:
setContentView() 之后调用ButterKnife.bind(Context context);
e.g.
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
使用时每个Activity 都要这样调用,所以可以改进一下,构造基类:
public abstract class BaseActivity extends AppCompatActivity {
public abstract int getContentViewId();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
ButterKnife.bind(this);
}
}
绑定UI 控件:
将光标放在布局文件id 上,command+n 选择Generate Butterknife Injections
在弹出的窗口就可以选择要生成的控件了。
其他用法:
// bind color
@BindColor(R.color.colorPrimary)
int colorPrimary;
// bind drawable
@BindDrawable(R.mipmap.ic_launcher)
Drawable mDrawable;
// bind string
@BindString(R.string.hello)
String greeting;
// binde view
@BindView(R.id.btn_greeting)
Button mBtnGreeting;
在Fragment 中
参照Activity 中的用法,构建基类
public abstract class BaseFragment extends Fragment {
public abstract int getContentViewId();
protected Context mContext;
protected View mRootView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getContentViewId(), container, false);
ButterKnife.bind(this, mRootView);
mContext = getActivity();
return mRootView;
}
}
在Adapter 中
在getView() 方法中,将光标置于布局文件id 上,command+n
即可生成ViewHolder,效果如下
本文项目Github地址:https://github.com/chinglimchan/ButterKnifeDemo