今天分享一种viewBinding视图绑定的用法,如果还没有了解过viewBinding的小伙伴可以先去了解一下viewBinding,下面这篇文章有助于你了解viewBinding Android视图绑定viewBinding的使用
多说无益,直接上代码
步骤
- 启用viewBinding,在build.gradle中配置一下
android{
....
viewBinding {
enabled = true
}
}
- 编写一个基类BaseActivity
public class BaseActivity<Binding extends ViewBinding> extends AppCompatActivity {
protected Binding binding;
@Nullable
protected Binding viewBindingInflate(LayoutInflater inflater) {
return null;
}
public Binding getBinding() {
return binding;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = viewBindingInflate(getLayoutInflater());
setContentView(binding.getRoot());
}
- 在activity_main.xml布局文件中添加一个TextView组件
<TextView
android:id="@+id/tv_hello"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello world">
</TextView>
- 在活动类MainActivity继承BaseAcitivity,并指定泛型为activity_main的绑定类ActivityMainBinding
public class MainActivity extends BaseActivity<ActivityMainBinding> {
@Nullable
@Override
protected ActivityMainBinding viewBindingInflate(LayoutInflater inflater) {
return ActivityMainBinding.inflate(inflater);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding.tvHello.setText("你好");
}
- 运行测试一下,发现TextView的文本为你好
本文就到这里,喜欢的朋友能给一个免费的赞嘛,你的鼓励是我前进的动力!
|