Android Butterknife 采坑记录

子module中使用

在Library module中使用参考:https://github.com/JakeWharton/butterknife#library-projects

Now make sure you use R2 instead of R inside all Butter Knife annotations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ExampleActivity extends Activity {
@BindView(R2.id.user)
EditText username;
@BindView(R2.id.pass)
EditText password;

@OnClick({R2.id.btn_alipay, R2.id.btn_wechat})
void onClick(View view) {
int id = view.getId();
if (id == R.id.btn_alipay) {

} else if (id == R.id.btn_wechat) {

}
}
}

成员变量不能使用private修饰

1
@BindView fields must not be private or static.

参考:https://github.com/JakeWharton/butterknife/issues/518

  • 错误姿势
1
2
3
4
@BindView(R2.id.btn_success)
private Button btnSuccess;
@BindView(R2.id.btn_failure)
private Button btnFailure;
  • 正确姿势
1
2
3
4
@BindView(R2.id.btn_success)
Button btnSuccess;
@BindView(R2.id.btn_failure)
Button btnFailure;

Fragment中绑定

1
2
3
4
5
6
7
8
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.bind(this, view);
initView(view);
return view;
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :