Android ViewBinding 的简单使用
程序员文章站
2022-06-05 12:39:03
...
前置
AndroidStudio至少要升级到3.6
配置启动
android {
...
viewBinding {
enabled = true
}
...
}
自动生成的代码位置
在Activity中使用
private ActivityMain2Binding viewBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewBinding = ActivityMain2Binding.inflate(LayoutInflater.from(this));
setContentView(viewBinding.getRoot());
viewBinding.tvText1.setText("123");
viewBinding.tvText2.setText("456");
viewBinding.tvText3.setText("789");
}
在Fragment中使用
private FragmentHomeBinding viewBinding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
viewBinding = FragmentHomeBinding.bind(root);
viewBinding.textHome.setText("123");
viewBinding.btConfirm.setText("456");
viewBinding.btConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Main2Activity.start(getContext());
}
});
return root;
}
上一篇: 华为Mate 20 Pro到手价3769元:徕卡三摄+麒麟980
下一篇: 不要紧来抽一根先