This paper mainly summarizes various view binding schemes, briefly introduces their principles and advantages and disadvantages, and uses them as work summary, technical collation and sharing training

The outline of this paper is as follows:

Overview of this paper:

The best way to bind a view is viewBinding. If you are using jetpack in your project and want to use databinding, you don’t need to use viewBinding.

Android base API -> findViewById

1.1 This method is not much to say will be mentioned later, everyone can use;

  • Need to pay attention to the control of the layout level, the core of the page drawing is to loop through THE ID to draw, so the layoutRequire a clear layout as far as possible&&Do not exponentially increase layout levels, traversing the core code is shown in the following figure:

1.2 Layout efficiency can be referred to the following articles:

Blog.csdn.net/qq_21154101…

Second, the ButterKnife

2.1 Warehouse Address:

Github.com/JakeWharton… Shows how to integrate butterKnife and so on

2.2 implementation principle: annotationProcessor/Kapt precompiled annotationProcessor

2.3 Advantages: Simplified findViewById heavy workload and exception protection

  • In addition, butterKnife’s As plug-in can generate annotation fields corresponding to IDS in XML with one key, without the need for developers to manually write annotation correspondence, which further improves development efficiency

2.4 Summary: Having been so excellent and operated for so many years, why do you voluntarily give up continuing maintenance?

2.4.1 In terms of implementation principle, the core principle of ViewBinding is neither too backward nor more advanced than the latest scheme!

2.4.2 The cost of upgrading multi-version projects of ButterKnife itself is also a problem. Upgrading from a low version to a high version involves the updating of syntax and does not support insensitive upgrade, which leads to common problems of open source libraries, such as many developers simply stick to the old version and the old project will not be updated. Even so, it has been used by countless developers for more than 5 years.

2.4.3 Because several later waves including Google have officially achieved a complete leapfrog over ButterKnife on the shoulders of giants, the integration is simpler, the integrated library is more lightweight, and the use of ButterKnife is easier. The comparison will be made later. The developers of ButterKnife are also aware of this problem and give up the maintenance of 😢. Thanks for being with us for so many years, and hopefully the ButterKnife team can contribute more good things to the open source community!

Kotlin Android Extensions

Google has pushed Android development to move to Kotlin, which is being developed by JetBrains, so their KTX plugin is seen as a solution to view binding. Do you know which company made the Android Studio development tool you use every day ❓

Advantages: easy to use,ALT+Enter according to promote the introduction of the file!

Disadvantages: Because it is too simple, the update efficiency is higher, but leads to too many problems as follows:Summary: By introducing the problems it can cause, developers have forgotten its advantages. Personal Kotlin small projects can also be used, but have few advantages over View Binding.

Four, viewbinding

4.1 Concept endorsement:

Google’s Jetpack is a suite of libraries that help developers follow best practices, reduce boilerplate code and write code that runs consistently across Android versions and devices, To let developers focus on writing important code, viewBinding is a component in Jetpack that is relatively easy to get started with

4.2 Integration and Settings:

4.2.1 Requirements

View binding is available in Android Studio 3.6 Canary 11 and later.Copy the code

4.2.2 Enabling View Binding

android {
 viewBinding {
  enabled = true
   }
}
Copy the code

4.2.3 Ignore view binding of a layout file

<LinearLayout
 tools:viewBindingIgnore="true" >
</LinearLayout>
Copy the code

4.3 Instructions:

4.3.1 XML file: activity_main.xml

<? The XML version = "1.0" encoding = "utf-8"? > <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:background="@drawable/background" tools:context=".main.MainActivity"> <com.google.android.material.tabs.TabLayout android:id="@+id/tablayout" style="@style/tabLayoutStyle" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:tabMaxWidth="200dp" app:tabMinWidth="50dp" app:tabMode="scrollable"></com.google.android.material.tabs.TabLayout> </androidx.constraintlayout.widget.ConstraintLayout>Copy the code

4.3.2 Automatically Generating Binding Class Files:

4.3.3 Use Binding to generate classes to load setContentView directly. Default is recommended

/ / get binding class instance binding = ActivityMainBinding. Inflate (layoutInflater) / / through binding classes for layout, SetContentView (binding.root) // Get the corresponding ID view from the binding class, Operate the binding. Tablayout. SetupWithViewPager (binding. Viewpaper);Copy the code

4.3.4 Base class encapsulation use, more concise, no need for developers to care about configuration view code, base class JVM reflection loading

  • Fragments using:

  • Use the Activity:

  • Activity base class code encapsulation:
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {

    protected T binding;
    private String mClassName = BaseActivity.class.getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (T) method.invoke(null, getLayoutInflater());
            setContentView(binding.getRoot());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//            Logger.error(mClassName, " onCreate Error");
            e.printStackTrace();
        }

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initViews();
        initDatas();
    }

    /**
     * 初始化布局View
     */
    protected abstract void initViews();

    /**
     * 初始化数据
     */
    protected abstract void initDatas();

}
Copy the code

4.4 Principle Analysis:

  • The viewBinding automatically generates the binding code in a precompiled manner

  • Do you remember the inflate function 🤔

  • At the core is the bind function, which returns our ActivityMainBinding object and, if you noticed, does a null security check 😘

  • Bind function
  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.line;
      View line = rootView.findViewById(id);
      if (line == null) {
        break missingId;
      }

      id = R.id.tablayout;
      TabLayout tablayout = rootView.findViewById(id);
      if (tablayout == null) {
        break missingId;
      }

      id = R.id.viewpaper;
      ViewPager viewpaper = rootView.findViewById(id);
      if (viewpaper == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, line, tablayout, viewpaper);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
Copy the code

4.5 Thin Code

  • This is our common view definition

  • This is a common view initialization

  • This is the view definition and initialization using ButterKnife

  • This is using a viewBinding, the view just needs to be defined in XML and used directly

  • I can use findViewById without defining the view variable, do I need to cast it? Otherwise I can. Come on! And can you really find the ID that belongs to the current page? These viewbindings are available at 😇

4.5 conclusion:

Viewbingding advantages

  • Simple integration, easy to use, and almost no intrusion into the developer’s code (it just generates extra code that you can ignore, if you don’t explore its implementation, you can almost ignore)
  • Empty security check, prevent us from not initialized null pointer exception, who will make mistakes, the advantage of using the framework is to avoid making mistakes as far as possible, avoid low-level bugs (have you made a similar error, found after clap thigh 😛)!
  • To reduce the amount of code and improve development efficiency, pages using viewBinding can reduce the number of variable definitions and initialization functions by dozens to hundreds of lines, greatly increasing the unnecessary repetitive work of development
  • Simplifying code readability improves readability, and readability itself improves code quality, because complex pages with a lot of variable definitions and naming conventions are a pain in the ass, and initializing CVS is a pain in the ass!

Based on the above advantages, for UI page elements complex page, from coding to reduce null pointer bug, improve code quality and other comprehensive considerations, personal development of multiple APP pages can improve the development efficiency of pure UI development of each page by about 20% on average (except especially simple static pages).

Five, the databinding

5.1 Concept Differences:

5.2 Differences:

  • Layout does not require layout labels when using view binding
  • You cannot use viewBinding to bind a layout to data in XML (no binding expressions, no binding)
  • The main benefits of view binding are speed and efficiency. It has a shorter build time because it avoids the overhead and performance issues associated with data binding because the annotation processor affects the build time of the data binding.
  • In short, no view binding can do what data binding cannot (albeit at the cost of longer build times), but there are many things that data binding can do that view binding cannot.

Disadvantages:

  • It is not as efficient as Viewbingding view binding. It is not as efficient as DataBinding view binding based on annotation processor. (A bit like Nokia’s Big Brother, from all eyes, suddenly no longer)

5.3 Summary of Simple ICONS:

Type blackboard, view binding summary

  • If you don’t want to introduce too much Jetpack into your project, you can simply use viewBinding
  • If you enjoy researching frameworks and the rest of the company is supportive, consider incorporating the Jetpack suite

Jetpack expansion

  • ViewBinding solves the problem of viewBinding and improves the efficiency and quality of page development
  • LifeCycle effectively solves the non-lifecycle problems of business logic classes
  • ViewModel real data storage repository, to solve the problem of time sequence data loss, unless your page is actually destroyed (see the viewModel life cycle for more information)
  • Livedata makes your data dynamically observable, with its own observer mode, making data monitoring easier
  • DataBinding XML dataBinding, Livedata is used for bidirectional binding of data between logic and page (similar to the bidirectional binding of vue, react and other cross-platform development) (but Google is also pushing for the development of the xmlization of Compose technology, so you can not integrate if you are not using dataBinding. Compose optimization is interesting to watch, but not very easy to use yet.)

Jetpack extension summary:

LifeCycle +viewModel+viewBinding is a fundamental component of Jetpack that will greatly improve development efficiency and quality. It is safe and reliable and relatively inexpensive for mature Android developers to learn and start. If we decide to deeply integrate Jetpack during the framework build, in fact Livedata+dataBinding is the almost inevitable choice for binding groupings, which will be shared in a new article along with the source code and template code

Put your hands together, knock it off!!

The king of The South Court (For The Dream)