This article documents the different ways in which activities, fragments use DataBinding, and how data is shared between different fragments of an Activity

Open the DataBinding

First we need to start DataBinding in App Gradle

    // Turn on DataBinding
    dataBinding {
        enabled true
    }
Copy the code

Changing layout files

Then we need to turn the layout file on DataBinding. Below is the layout file with the switch completed. All we have to do is press Alt + Enter to see figure 1

Select Convert to Data Binding Layout to Convert to dataBinding Layout.

The specific use

The above has been converted to the Binding layout. After the conversion, the Activity/Fragment + Name + Binding object will be generated. Here we explain the use of activities and fragments separately

Activity

Take MainActivity for example,

	private ActivityMainBinding binding;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
	}

Copy the code

Fragment

	private FragmentHomeBinding binding;
	@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
        return binding.getRoot();
    }

Copy the code

From the above we can see that activities and fragments are used differently.

Data sharing

Finally, we will talk about the data sharing problem of multiple fragments under the Activity

So let’s talk about how it works, but the ViewModel is created like this

	MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
Copy the code

If the Fragment is created as a Fragment under the Activity, then we need to change this to the Activity that it is in to get the ViewModel corresponding to the Activity. Multiple fragments can then share data in the ViewModel.

  1. MainActivity First we create the ViewModel in the MainActivity
	MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
Copy the code
  1. HomeFragment
	MainViewModel viewModel = new ViewModelProvider(Objects.requireNonNull(getActivity())).get(MainViewModel.class);
Copy the code

And then it’s gone, and you can do whatever you want.