Chapter 20 Data Binding and MVVM
With your binding created, you can now get at your RecyclerView and configure it.
Listing 20.7 Configuring RecyclerView (BeatBoxFragment.java)
public class BeatBoxFragment extends Fragment {
public static BeatBoxFragment newInstance() {
return new BeatBoxFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentBeatBoxBinding binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_beat_box, container, false);
binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),
3));
return binding.getRoot();
}
}
This is what we call simple data binding – using data binding to automatically pull out views for you,
instead of writing findViewById(...). Later, you will see more advanced uses of data binding. For now,
though, you will continue wiring up your RecyclerView.
Next, create the layout for the buttons, res/layout/list_item_sound.xml. You will be using data
binding here, as well, so add a layout tag surrounding your layout file.
Listing 20.8 Creating sound layout (res/layout/list_item_sound.xml)
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<Button
android:layout_width="match_parent"
android:layout_height="120dp"
tools:text="Sound name"/>