ButterKnife 跨module使用

2020-05-28  本文已影响0人  cain07

Android开发中大部分都会存在多module的情况,但是butterKnife默认只支持在同一个module下的注解,在library是无法使用的,但是很多情况下我们可能有一个公共的lib,用于提供给其他module公共的utils和抽出的base类,那这种情况下,该如何使用butterKnife为不同的module提供注解功能呢。
使用步骤

1.需要2个以上的module,其中一个为app,其他为library
image

<center>图1-1</center>

2.在lib的gradle依赖中添加butterKnife库
image

<center>图2-1</center>

compile 'com.jakewharton:butterknife:8.5.1'
3.在app下的gradle添加annotationProcessor
image

<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();
}
5.在其他module下的Activity就可以继承BaseActivity,直接使用注解了
上一篇 下一篇

猜你喜欢

热点阅读