[Android] Use View Binding instead of findViewById

1.Configuration

Add configuration to the build.gradle file and then synchronize.

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

2. Use the View Binding class to access the views in the layout

Import the generated View Binding class at the top of the Activity code:

import com.example.yourapp.databinding.ActivityMainBinding

Create a View Binding object in the activity class and use the inflate method to get the bound view:

private lateinit var binding: ActivityMainBinding

In the activity's onCreate method, use the setContentView method to set the activity's view, and use the View Binding object to get the root view:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    // 现在您可以使用 binding 对象访问布局中的视图
    binding.textView.text = "Hello, World!"
}

3. Use View Binding in Fragment

In Fragment, you can use View Binding in onCreateView:

class MainFragment : Fragment() {

    private var _binding: FragmentMainBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.someView.text = "Hello, World!"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

In Fragment, we need to set _binding to null in onDestroyView. This is because the view may be destroyed before the Fragment is destroyed, so we need to avoid memory leaks between the Fragment and the view.

4. Ignore View Binding

If the layout file does not need to generate binding classes, you can add the tools:viewBindingIgnore="true" attribute to the root view of the layout file:

<LinearLayout
    ...
    tools:viewBindingIgnore="true" >
</LinearLayout>

Guess you like

Origin blog.csdn.net/u012881779/article/details/134409016