ViewBinding usage

ViewBinding usage

ViewBinding is a new library that can replace findViewById() to bind views. It is a type-safe, nullable way to access views in a view hierarchy. Compared with other binding libraries such as ButterKnife, ViewBinding is officially provided by Google and is simpler to use.

The steps to use ViewBinding are as follows:

  1. Add the following dependencies in the build.gradle file:
android {
    
    
    ...
    buildFeatures {
    
    
        viewBinding true
    }
}

dependencies {
    
    
    ...
    implementation 'com.android.support:viewbinding:28.0.0-alpha1'
}
  1. Add tags in the layout file, for example:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </LinearLayout>
</layout>
  1. Use ViewBinding to bind views in code, for example:
class MainActivity : AppCompatActivity() {
    
    

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.container.setOnClickListener {
    
    
            binding.textView.text = "You clicked me!"
        }
    }
}

In this example, we use ActivityMainBinding to bind the view in activity_main.xml. Create the binding object through the inflate() method, and then set the root view using the setContentView() method. Afterwards, we can access the view just like a normal layout.

The main benefit of using ViewBinding is that you avoid a lot of boilerplate code, and you avoid NullPointerExceptions at runtime because it uses Kotlin's nullable types.

Use ViewBinding in Activity

To use ViewBinding in Activity, you need to add the following dependencies in the build.gradle file:

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

dependencies {
  ...
  implementation 'com.android.support:viewbinding:28.0.0'
}

Next, add the following code to the Activity's layout file:

<LinearLayout
    ...
    >

    <TextView
        android:id="@+id/textView"
        ...
        />

    <Button
        android:id="@+id/button"
        ...
        />

</LinearLayout>

When using ViewBinding in Activity, you first need to declare a ViewBinding object in Activity and initialize it in the onCreate() method:

private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
}

Next, you can use the binding object to operate the controls in the layout:

binding.textView.setText("Hello World!");
binding.button.setOnClickListener(new View.OnClickListener() {
    
    
    @Override
    public void onClick(View v) {
    
    
        // do something
    }
});

It should be noted that ViewBinding will generate corresponding variable names for these controls based on the ids of the controls in the layout file, so you need to use the camelCase naming method when using it, such as the findViewById(R.id.text_view)corresponding ViewBinding variable name binding.textView.

In addition, it should be noted that if there are multiple layout files in the Activity, you need to use the corresponding ViewBinding object to operate the controls in different layout files, for example:

private ActivityMainBinding mainBinding;
private ActivityOtherBinding otherBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
    otherBinding = ActivityOtherBinding.inflate(getLayoutInflater());
    setContentView(mainBinding.getRoot()); // 设置默认布局
}

private void switchLayout(boolean isMain) {
    
    
    if (isMain) {
    
    
        setContentView(mainBinding.getRoot());
    } else {
    
    
        setContentView(otherBinding.getRoot());
    }
}

Use ViewBinding in Fragment

To use ViewBinding in Fragment, you need to perform the following steps in Fragment's onCreateView method:

  1. Define a ViewBinding object in the Fragment class, such as:
private var binding: FragmentExampleBinding? = null
  1. Get the ViewBinding object in the onCreateView method:
binding = FragmentExampleBinding.inflate(inflater, container, false)
  1. Return the root view of the ViewBinding:
return binding?.root
  1. Make sure to unbind when the Fragment is destroyed:
override fun onDestroyView() {
    
    
   super.onDestroyView()
   binding = null
}

Complete sample code:

class ExampleFragment : Fragment() {
    
    
   private var binding: FragmentExampleBinding? = null
   
   override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstanceState: Bundle?
   ): View? {
    
    
      binding = FragmentExampleBinding.inflate(inflater, container, false)
      
      return binding?.root
   }
   
   override fun onDestroyView() {
    
    
      super.onDestroyView()
      binding = null
   }
}

Guess you like

Origin blog.csdn.net/weixin_74239923/article/details/134805326