当前位置:   article > 正文

Android Jetpack视图绑定

android there is no generic of viewbinding

Basically, findViewById is one of the major troublesome boilerplate codes in Android development because it can lead to some unpredictable outcomes. There are provided some libraries to diminish this problem; however, each of them has some negative consequences in some areas such as speed, compile time, and easy to use. To address this problematic issue, Google has recommended View Binding library as an effective approach. This essay aims to consider View Binding library as an advanced method for dealing the problem of findViewById in Android development in order to increase the efficiency and performance.

基本上,findViewById是Android开发中主要的麻烦样板代码之一,因为它可能导致某些不可预测的结果。 提供了一些库来减轻此问题; 但是,它们每个都在某些方面带来一些负面影响,例如速度,编译时间和易于使用。 为了解决这个问题,Google建议使用View Binding库作为一种有效的方法。 本文旨在将视图绑定库视为一种高级方法,用于解决Android开发中的findViewById问题,以提高效率和性能。

概述与介绍 (Overview and Introduction)

Even though from Android 8 (API 26) Google improve the findViewById() by using generic type and returning a View type. Using a View without adding null checks can lead to NullPointerException because findViewById is not null safe indeed. As a result, Google has introduced View binding as a new approach in addition to Data binding because it is a lighter weight solution for replacing findViewById without using the rest of the Data binding library features. In other words, it could be a useful solution for avoiding the performance issues of Data binding, and could be an alternative way for supporting compile-time safety as well. In fact, instead of having to look up every view, it generates a binding object that holds all the view for you. View binding adds safety. When you inflate a view, the binding object will automatically provide you the exact type. Thus, the main benefits of View Binding over Data binding are speed and efficiency because annotation processing in Data binding can affect on increasing the build time. Furthermore, you can use this library in Java and Kotlin programming in practice.

即使从Android 8(API 26)开始,Google仍通过使用泛型类型并返回View类型来改进findViewById()。 使用View而不添加null检查会导致NullPointerException,因为findViewById确实不是null安全的。 结果,除了数据绑定之外,Google还引入了视图绑定作为一种新方法,因为它是一种轻量级的解决方案,可替代findViewById,而无需使用数据绑定库的其余功能。 换句话说,它对于避免数据绑定的性能问题可能是有用的解决方案,并且也可能是支持编译时安全性的替代方法。 实际上,它不必查找每个视图,而是会生成一个绑定对象,为您保留所有视图。 视图绑定增加了安全性。 给视图充气时,绑定对象将自动为您提供确切的类型。 因此,视图绑定相对于数据绑定的主要好处是速度和效率,因为数据绑定中的注释处理可能会影响构建时间。 此外,您可以在实践中在Java和Kotlin编程中使用此库。

View binding is a feature that allows you to more easily write code that interacts with views.

视图绑定是一项功能,使您可以更轻松地编写与视图交互的代码。

在Gradle中启用视图绑定 (Enabling View Binding in Gradle)

Basically, view binding needs Android Studio and the Android Gradle plugin 3.6.0 or higher. To use it in your module, enable it in your build.gradle file. You do not require to include any library or dependency to use view binding. So, to enable view binding in a module, add the viewBinding element to its build.gradle file as follows:

基本上,视图绑定需要Android Studio和Android Gradle插件3.6.0或更高版本。 要在模块中使用它,请在build.gradle文件中启用它。 您不需要包括任何库或依赖项即可使用视图绑定。 因此,要在模块中启用视图绑定,请按如下所示将viewBinding元素添加到其build.gradle文件中:

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

In Android Gradle Plugin 4.0 or higher, viewBinding has been changed into buildFeatures and you must use as below:

在Android Gradle Plugin 4.0或更高版本中,viewBinding已更改为buildFeatures ,您必须按以下方式使用:

android {    ...    buildFeatures {        viewBinding = true    }}

Initially, when you enable view binding in a module, it generates a binding class for each XML file in that module. So, an instance of a binding class holds direct references to all views that have an ID in related to the layout. In most situations, view binding replaces findViewById. In addition, if you want a layout file to be ignored when generating binding classes, you should add the tools:viewBindingIgnore="true" attribute to the root view of that layout file.

最初,当在模块中启用视图绑定时,它将为该模块中的每个XML文件生成一个绑定类。 因此,绑定类的实例持有对所有具有与布局有关的ID的视图的直接引用。 在大多数情况下,视图绑定会替换findViewById 。 另外,如果希望在生成绑定类时忽略布局文件,则应将tools:viewBindingIgnore="true"属性添加到该布局文件的根视图。

在活动中使用视图绑定 (Using View Binding in an Activity)

When you enable the compiler for view binding, it will automatically recompile your Android project, and generate binding objects for each layout. Therefore, if you have a layout file called activity_main.xml, view binding will generate a small class called ActivityMainBinding. In fact, the name of the binding class is produced by converting the name of the XML file to camel case and adding the word “Binding” to the end. For instance:

当您启用编译器进行视图绑定时,它将自动重新编译您的Android项目,并为每个布局生成绑定对象。 因此,如果您有一个名为activity_main.xml的布局文件,则视图绑定将生成一个名为ActivityMainBinding的小类。 实际上,绑定类的名称是通过将XML文件的名称转换为驼峰大小写并在单词末尾添加“ Binding”来产生的。 例如:

<LinearLayout ... >    <TextView android:id="@+id/sampleName" />    <ImageView android:cropToPadding="true" />    <Button android:id="@+id/sampleButton"        android:background="@drawable/rounded_button" /></LinearLayout>

This class has two fields: a TextView called sampleName and a Button called sampleButton. As you notice, The ImageView in the layout has no ID; therefore, there is no reference related to it in the binding class. Also, any binding class contains a getRoot() method. So, in above example, the getRoot() method in the class returns the LinearLayout root view.

此类具有两个字段:一个名为sampleName的TextView和一个名为sampleButton的Button。 如您所见,布局中的ImageView没有ID。 因此,在绑定类中没有与此相关的引用。 此外,任何绑定类都包含getRoot()方法。 因此,在上面的示例中,类中的getRoot()方法返回LinearLayout根视图。

Currently, to set up an instance of the binding class for using in an activity, you should call the static inflate() method, and then you should obtain a reference to the root view by either calling the getRoot() method or using Kotlin property syntax. Eventually, you must pass the root view to setContentView() as follows:

当前,要设置在活动中使用的绑定类的实例,应调用static inflate()方法,然后应通过调用getRoot()方法或使用Kotlin属性来获取对根视图的引用。 语法 。 最终,必须将根视图传递给setContentView() ,如下所示:

private lateinit var binding: sampleBindingoverride fun onCreate(savedInstanceState: Bundle) {    super.onCreate(savedInstanceState)    binding = SampleBinding.inflate(layoutInflater)    val view = binding.root    setContentView(view)}

Now, you can be able to use the instance of the binding class to reference any of the views:

现在,您可以使用绑定类的实例来引用任何视图:

binding.sampleButton.setOnClickListener(new View.OnClickListener() {    viewModel.userClicked()});

在片段中使用视图绑定 (Using view binding in a fragment)

Similarly, you should us view binding in a fragment in three steps. First of all, you should call the static inflate() method, and then you should obtain a reference to the root view by either calling the getRoot() method or using Kotlin property syntax.

同样,您应该分三步查看片段中的绑定。 首先,您应该调用静态inflate()方法,然后应该通过调用getRoot()方法或使用Kotlin属性语法来获取对根视图的引用。

Types of inflate() method:

inflate()方法的类型:

  • inflate(inflater): you must use this type in an Activity’s onCreate() that there is no parent view for passing.

    inflate(inflater):您必须在没有父视图传递的Activity的onCreate()中使用此类型。

  • inflate(inflater, parent, attachToParent): you must use this type in a Fragment or a RecyclerView’s Adapter that you have to pass the parent to the binding object.

    inflate(inflater(inflater,parent,parent,attachToParent)):必须在必须将父级传递给绑定对象的Fragment或RecyclerView的Adapter中使用此类型。

Finally, you must return the root view from the onCreateView() method. However, make sure you clean up any references to the binding class instance in the fragment’s onDestroyView() method.

最后,您必须从onCreateView()方法返回根视图。 但是,请确保您清除了片段的onDestroyView()方法中对绑定类实例的所有引用。

数据绑定和视图绑定之间的区别 (Differences between data binding and view binding)

Although data binding and view binding are null safety (there is no risk of a null pointer exception) and type safety (there is no risk of a class cast exception), view binding can be able to manage simpler use cases and, can provide the following advantages over data binding:

尽管数据绑定和视图绑定是 使用null安全性 (不存在null指针异常的风险)和类型安全性 (不存在类强制转换异常的风险),视图绑定可以管理更简单的用例,并且与数据绑定相比具有以下优点:

  1. Compile times are faster due to no annotation processing.

    由于没有注释处理,因此编译时间更快。
  2. Usability: view binding does not need special tag in your XML layout files. Thus, it would be easy in implementing for developer.

    可用性:视图绑定在XML布局文件中不需要特殊标记。 因此,对于开发人员来说很容易实现。

结论 (In conclusion)

As a matter of fact, findViewById is one of the major challenges in Android development because it can cause some unpredictable behaviors and results. Even though there are provided some libraries to diminish this problem, each of them has some negative consequences in some areas such as speed, compile time, and easy to use. In this article, view binding introduced and discussed as an effective approach for dealing this issue in Android, which is recommended by Google in addition to data binding in Android projects. Null safety, type safety, easy to use, and faster compilation are some of the important benefits of this feature in Android development.

事实上, findViewById是Android开发中的主要挑战之一,因为它可能会导致某些无法预测的行为和结果。 即使提供了一些库来减轻此问题,但它们每个都在某些方面产生了一些负面影响,例如速度,编译时间和易于使用。 在本文中,介绍并讨论了视图绑定,这是在Android中解决此问题的有效方法,除Android项目中的数据绑定外,Google还建议使用视图绑定。 空安全性,类型安全性,易于使用和更快的编译速度是Android开发中此功能的一些重要优点。

翻译自: https://medium.com/kayvan-kaseb/android-jetpack-view-binding-4758c729ebe3

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/486850
推荐阅读
相关标签
  

闽ICP备14008679号