Android开发中大部分都会存在多module的情况,但是butterKnife默认只支持在同一个module下的注解,在library是无法使用的,但是很多情况下我们可能有一个公共的lib,用于提供给其他module公共的utils和抽出的base类,那这种情况下,该如何使用butterKnife为不同的module提供注解功能呢。
使用步骤
1.需要2个以上的module,其中一个为app,其他为library
<center>图1-1</center>
2.在lib的gradle依赖中添加butterKnife库
<center>图2-1</center>
compile 'com.jakewharton:butterknife:8.5.1'
3.在app下的gradle添加annotationProcessor
<center>图3-1</center>
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
4.在lib的module下添加BaseActivity/BaseFragment
示例Activity
public abstract class BaseActivity extends Activity {
protected Unbinder mUnbinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
mUnbinder = ButterKnife.bind(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mUnbinder != mUnbinder.EMPTY){
mUnbinder.unbind();
}
}
protected abstract int getLayoutId();
}
示例Fragment
public abstract class BaseFragment extends Fragment {
protected Unbinder mUnbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(getLayoutId(),container,false);
mUnbinder = ButterKnife.bind(this,rootView);
return rootView;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mUnbinder != mUnbinder.EMPTY){
mUnbinder.unbind();
}
}
protected abstract int getLayoutId();
}
网友评论