dependencies { // Adds the local "mylibrary" module as a dependency to the "free" flavor. freeImplementation project(":mylibrary") testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
2.会根据布局文件,编译之后自动生成对应的Binding class,可以在Activity 和 Fragment 直接调用 inflate 使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
privatevar _binding: ResultProfileBinding? = null // This property is only valid between onCreateView and // onDestroyView. privateval binding get() = _binding!!
val binding: ActivityMainBinding = ActivityMainBinding.inflate(getLayoutInflater()) // or val binding: ActivityMainBinding = DataBindingUtil.setContentView( this, R.layout.activity_main)
binding.user = User("Test", "User") }
在 Fragment, ListView, or RecyclerView adapter, you may prefer to use the inflate()
1 2 3
val listItemBinding = ListItemBinding.inflate(layoutInflater, viewGroup, false) // or val listItemBinding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false)
0x03 view binding 和 data binding 比较
View binding and data binding both generate binding classes that you can use to reference views directly. However, view binding is intended to handle simpler use cases and provides the following benefits over data binding:
Faster compilation: View binding requires no annotation processing, so compile times are faster.
Ease of use: View binding does not require specially-tagged XML layout files, so it is faster to adopt in your apps. Once you enable view binding in a module, it applies to all of that module’s layouts automatically.
Conversely, view binding has the following limitations compared to data binding:
Because of these considerations, it is best in some cases to use both view binding and data binding in a project. You can use data binding in layouts that require advanced features and use view binding in layouts that do not.
0x04 遇到的坑
等标签,如果使用databinding ,子布局xml的 root tag 依旧需要layout 标签嵌套 data 标签。否者编译报错,找不到对应的属性
/** * 调整状态栏文字、图标颜色 > 6.0 * true:白底黑字,false:黑底白字 */ funlightStatusBar(activity: Activity, light: Boolean = true) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return var window: Window = activity.window var visibility = window.decorView.systemUiVisibility visibility = if (light) { visibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { visibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } window.decorView.systemUiVisibility = visibility }
// 获取状态栏高度 fungetStatusBarHeight(activity: Activity): Int { var result: Int = 0 var resId = activity.resources.getIdentifier("status_bar_height", "dimen", "android") if (resId > 0) result = activity.resources.getDimensionPixelOffset(resId) return result } }