ViewBinding使用详解
-
使用ViewBinding时需要先在build.gradle文件中声明
//老版本 viewBinding { enabled = true } //新版本 buildFeatures { viewBinding = true }
-
生成绑定类时忽略某个布局文件,请将
tools:viewBindingIgnore="true"
属性添加到相应布局文件的根视图中:<LinearLayout ... tools:viewBindingIgnore="true" > ... </LinearLayout>
-
使用
假设activity_main.xml为布局文件,所生成的绑定类的名称就为
ActivityMainBinding
private lateinit var binding: ResultProfileBinding override fun onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) binding = ResultProfileBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.name.text = viewModel.name binding.button.setOnClickListener { } }
-
在Fragment中的视图绑定
kotlin
private var _binding: ResultProfileBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = ResultProfileBinding.inflate(inflater, container, false) val view = binding.root return view } override fun onDestroyView() { super.onDestroyView() _binding = null }
java
private ResultProfileBinding binding; @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = ResultProfileBinding.inflate(inflater, container, false); View view = binding.getRoot(); return view; } @Override public void onDestroyView() { super.onDestroyView(); binding = null; }
-
视图绑定不支持布局变量或布局表达式,因此不能用于直接在 XML 布局文件中声明动态界面内容。
-
视图绑定不支持双向数据绑定。