google-developer-training / first-android-app

Repository for Build Your First Android App codelabs (Java and Kotlin)
7 stars 6 forks source link

First Android App codelab: Task 8 (make interactive) needs binding update #141

Open skgoetz opened 3 years ago

skgoetz commented 3 years ago

This note is for steps 3 and 4, make the Count button update and cache the TextView.

The Java code snippet that ends step 4 is out of date and doesn't work with Android Studio's current templates. Please update it to support view bindings.

Right now the tutorial says,

TextView showCountTextView;

@Override
public View onCreateView(
       LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState
) {
   // Inflate the layout for this fragment
   View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
   // Get the count text view
   showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);

   return fragmentFirstLayout;
}

Instead, something like this:

private FragmentFirstBinding binding;
TextView showCountTextView;

@Override
public View onCreateView(
        LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState
) {
    // Inflate the layout for this fragment
    binding = FragmentFirstBinding.inflate(inflater, container, false);
    View fragmentFirstLayout = binding.getRoot();
    // Get the count text view
    showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);

    return fragmentFirstLayout;
}
MaximumRide93 commented 2 years ago

this solution is great (and it works) but maybe point out that you need to remove the binding = FragmentFirstBinding.inflate(inflater, container, false); return binding.getRoot(); part that is loaded in there by default - as the app won't run with both pieces of code (the solution and the aforementioned code), it just throws errors saying 'code unreachable' or something.