官方文档:https://developer.android.google.cn/topic/libraries/view-binding?hl=zh-cn#java
- 在app module下的build.gradle文件中,添加ViewBinding配置:
viewBinding {
enabled = true
}
如下图:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
mBinding.tvHello.setText("ViewBindingDemo");
}
}
源码分析
- inflate()方法中根据layoutId生成View对象root,然后调用了bind()方法:
- bind()方法中,调用ActivityMainBinding构造方法,初始化
ActivityMainBinding 对象,并且调用了findViewById()初始化tvHello:
|