开源库(1) - ButterKnife 的使用

这一系列文章,将整理Retrofit、RxJava(RxAndroid)、Dagger2、ButterKnife 等几个开源库的结合使用学习笔记,希望自己能够在Android 开发上有更大的进步。

好!现在就从ButterKnife 开始啦!

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值