Android的ViewBinding

ViewBinding can easily bind the xml file that defines the view, making it easier and more convenient to write code that interacts with UI controls.
1. Configure ViewBinding
To use ViewBinding technology, you need to configure viewBinding in the build.gradle of the corresponding application module.
There are two specific configuration methods:
(1) Only used in the Kotlin language version

   android {
    
    
        ...
        viewBinding {
    
    
            enabled = true
        }
    }

(2) Can be used in Java/Kotlin language, then configure

   android {
    
    
        ...
        buildFeatures {
    
    
            viewBinding true
        }
    }

2. Apply ViewBinding
1. Define the layout file activity_main.xml of MainActivity as shown below:


<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />
```

2. 在MainActivity修改TextView的内容执行如下代码:

class MainActivity : AppCompatActivity() {
lateinit var binding:ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContent(binding.root)
    binding.textView.text="viewBinding的应用"
    }
}

因为在模块中启用viewBinding绑定之后,系统会为该模块中的每个 XML 布局文件生成一个绑定类。绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。

参考文献
https://developer.android.google.cn/topic/libraries/view-binding?hl=zh-cn

Guess you like

Origin blog.csdn.net/userhu2012/article/details/127545136