View Binding方法怎么用
时间: 2024-01-08 18:04:23 浏览: 30
使用 View Binding 方法绑定控件需要进行以下步骤:
1. 在 module 的 build.gradle 文件中添加如下代码:
```
android {
...
buildFeatures {
viewBinding true
}
}
```
2. 在需要绑定控件的布局文件中添加 <layout> 标签,将布局文件的根布局放在该标签内。
3. 构建项目后,会生成对应布局文件的绑定类,类名为布局文件名加上 Binding 后缀。
4. 在需要绑定控件的 Activity 或 Fragment 中,使用生成的绑定类来获取控件对象。
例如,如果有一个名为 activity_main.xml 的布局文件,可以按照以下方式获取其中的 TextView 控件:
```
// 初始化绑定类
val binding = ActivityMainBinding.inflate(layoutInflater)
// 获取 TextView 控件对象
val textView = binding.textView
```
需要注意的是,View Binding 方法只适用于 Android Studio 3.6 及以上版本。
相关问题
view binding方法怎么用
使用 View Binding 方法绑定控件需要进行以下步骤:
1. 在 module 的 build.gradle 文件中添加如下代码:
```
android {
...
buildFeatures {
viewBinding true
}
}
```
2. 在需要绑定控件的布局文件中添加 <layout> 标签,将布局文件的根布局放在该标签内。
3. 构建项目后,会生成对应布局文件的绑定类,类名为布局文件名加上 Binding 后缀。
4. 在需要绑定控件的 Activity 或 Fragment 中,使用生成的绑定类来获取控件对象。
例如,如果有一个名为 activity_main.xml 的布局文件,可以按照以下方式获取其中的 TextView 控件:
```
// 初始化绑定类
val binding = ActivityMainBinding.inflate(layoutInflater)
// 获取 TextView 控件对象
val textView = binding.textView
```
需要注意的是,View Binding 方法只适用于 Android Studio 3.6 及以上版本。
viewBinding bind 使用
使用 ViewBinding 的 `bind` 方法需要先在布局文件中进行配置。在布局文件的根节点上添加 `android:id` 属性,属性值为 `@+id/xxx`,其中 `xxx` 是你自己指定的名称,如下所示:
```xml
<LinearLayout
android:id="@+id/layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
```
然后在对应的 Activity 或 Fragment 中,通过如下方式获取绑定类对象:
```kotlin
private lateinit var binding: ActivityMainBinding // ActivityMainBinding 是根据布局文件名生成的类
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
```
在获取绑定类对象后,就可以通过该对象直接访问布局文件中的各种 UI 组件了,如下所示:
```kotlin
binding.tvTitle.text = "Hello ViewBinding!"
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)