Android - 用 Butterknife 替换 findViewById

Android - replace findViewById with Butterknife

我已经成功用 Butterknife 库替换了 findViewByIds。 不幸的是,出现了一个问题:

final Button btnPopup = (Button) popupView.findViewById(R.id.btn_popup); //popupView.findViewById(...) problem!!!

如何更改 Butterknife 中的这行代码:因为 Butterknife.bind(this); 占用了整个活动 Views

使用

将 popupView 绑定到主视图
View popupView = View.inflate(getContext(), R.layout.yourPopup, null);
ButterKnife.bind(this,popupView);

或者您可能想直接使用

绑定它
Button btnPopup = ButterKnife.findById(popupView, R.id.btn_popup);

首先,为了使用 ButterKnife 库,添加了两个依赖项:

Buil.gradle

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

然后,在使用@BindView上面的onCreate方法之后,在方法里面写ButterKnife(this, "any other unrelated views to this layout")

"any other unrelated views to this layout" 可以是另一个布局的内容,例如 Popup window 或 ....