在开始之前,假设存在某个布局文件,名称为 result_profile.xml
:
<LinearLayout ... >
<TextView android:id="@+id/name" />
<ImageView android:cropToPadding="true" />
<Button android:id="@+id/button" android:background="@drawable/rounded_button" />
</LinearLayout>
现在你要在java文件中查找该布局文件中的view。
你是否仍然使用findViewById
查找view?
class ExampleActivity extends Activity {
private TextView tv;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_profile);
initView();
}
private void initView() {
tv = findViewById(R.id.name);
btn = findViewById(R.id.button);
}
}
反复的findViewById有没有觉得很累,有没有更优雅的方式?
使用Butter Knife更优雅的查找view
Butter Knife是一个专注于Android系统的View注入框架,通过在字段上使用@BindView
代替indViewById
调用。
class ExampleActivity extends Activity {
@BindView(R.id.name) TextView tv;
@BindView(R.id.button) private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_profile);
ButterKnife.bind(this);
}
}
当然,Butter Knife的功能不仅仅如此哦!它还可以
Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick
and others.
Eliminate resource lookups by using resource annotations on fields.
集成方式,请见butterknife
view binding
若你现在访问Butter Knife,你会发现Butter Knife目前已弃用,它推荐你使用view binding。View Binding是什么呢?
View Binding是Android Studio 3.6推出的新特性,目的是为了替代findViewById
(内部实现还是使用findViewById)。
class ExampleActivity extends Activity {
private ResultProfileBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ResultProfileBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
}
...
binding.getName().setText(viewModel.getName());
binding.button.setOnClickListener(new View.OnClickListener() {
viewModel.userClicked()
});
}
由于View Binding是Android Studio 3.6推出的新特性,升级Android Studio 至3.6及以上版本即可直接使用。
更多资料请见官方文档