ButterKnife 的使用

under Android  tag     Published on June 10th , 2021 at 04:32 pm

ButterKnife 特点:简化代码,增强可读性。

ButterKnife 项目地址:https://github.com/JakeWharton/butterknife

添加依赖

android{
    //... ... 
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies{
    //... ...
    implementation 'com.jakewharton:butterknife:10.1.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
}

使用

  • Activity

在 onCreate() 中添加

ButterKnife.bind(this);
注意:必须添加在 setContentView(R.layout.activity_main) 后面

// 绑定控件
@BindView(R.id.et_name) EditText etName;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    ButterKnife.bind(this);
}

// 点击事件
@onClick(R.id.tv_login)
public void onViewClicked(){
    //... ...
}

// 多个控件的点击事件
@onClick({R.id.tv_btn, R.id.tv_click})
public void onViewClicked(View view){
    //... ...
}
  • Fragment

在 onCreateView() 中添加

ButterKnife.bind(this, view);

// 其余部分和 Activity 用法一样
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, null);
    
    ButterKnife.bind(this, view);
    return view;
}
  • Adapter

在 ViewHolder 中添加

ButterKnife.bind(this, view);

@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;
    if (view != null) {
      holder = (ViewHolder) view.getTag();
    } else {
      view = inflater.inflate(R.layout.item, parent, false);
      holder = new ViewHolder(view);
      view.setTag(holder);
    }

    holder.name.setText("admin");
    //... ...
}

static class ViewHolder {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
      ButterKnife.bind(this, view);
    }
}
  • 绑定资源文件
@BindColor(R.color.colorBlack) int colorBlack;
@BindDrawable(R.drawable.ic_launcher_foreground) Drawable icLauncher;

可能报错

出现这个错误多半是 ButterKnife 找不到控件了

Required view 'et_name' with ID 2131230873 for field 'etName' was not found.

If this view is optional add '@Nullable' (fields) or '@Optional' (methods) annotation.

原因:我写了一个抽象类 BaseActivity,在 BaseActivity 中写了
ButterKnife.bind(this),但是没有指定的 layout,所以 ButterKnife 找不到控件。

解决:在 BaseActivity 里写了一个抽象方法

public abstract class BaseActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        
        ButterKnife.bind(this);
    }
    
protected abstract int getLayoutResId();

本文由 surface 创作,采用 知识共享署名4.0 国际许可协议进行许可,转载前请务必署名
  文章最后更新时间为:September 29th , 2021 at 04:37 pm
分享到:Twitter  Weibo  Facebook