Modify the layout of a fragment
Same as in the use of activity, the use of data binding in fragment also needs to modify the layout, the same way as the activity, the outermost add <layout> tags:
<?xml version="1.0" encoding="utf-8"?><layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> </data> <页面布局.../></layout>
Similarly, in order to avoid repetition, the data binding in <data> is covered in this article.
Binding in Fragment
There are some differences in how bindings are created in activity, but the purpose is to obtain a reference to the bound object.
For example, our fragment layout file is: Frag_main.xml, the specific way is as follows:
- Defining member variables
private FragMainBinding mBinding;
- Initialize the mbinding in Oncreateview () and return to the view
@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mBinding = FragMainBinding.inflate(inflater); mBinding.tvExample.setText("Binding Text"); return mBinding.getRoot();}
At this point, the binding object can be operated normally.
Summarize
Similar to getting the data binding object in activity, the method is slightly different.
In addition to using data binding in activity and fragment, another common scenario is to use data binding in the adapter of a list, as we'll talk about.
In the next article, we'll start by explaining how <data> tags work in layouts, that is, how to bind data to a layout file.
Android development Tutorial-Using Data Binding (iv) in fragment