I have an issue with ViewBinding in a Fragment for an EditText line in the Activity. The Fragment launches a dialog to ask a user if they want to clear the EditText line. The EditText line is set up as "CEditText" in the Activity's xml file (activity_edit.xml). CEditText is used in the Fragment to clear the EditText line when the user confirms via the Fragment's dialog button press.
When I try to replace the previous working code "...findViewById(R.id.CEditText)" to add the binding reference for CEditText, Android Studio doesn't "see" the CEditText variable. I did try to inflate() ActivityEditBinding in onCreateView() and onViewCreated() of the Fragment and also tried to bind() it in each method but no luck.
What am I missing here?
public class SkycardClearFragment extends DialogFragment {
private SkyfragClearBinding binding15;
private ActivityEditBinding binding16; //AS says "field is never assigned"
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding15 = SkyfragClearBinding.inflate(inflater,container,false);
return binding15.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceSate) {
Button btnClearOK = binding15.btnClearOK;
btnClearOK.setOnClickListener(v -> {
if (getActivity() != null) {
// Create a reference to all of the EditTexts from the activity using the xml layout Ids.
**strong text**EditText ToDo = getActivity().getWindow().getDecorView().getRootView().binding16.CEditText; // AS error: "cannot resolve 'binding16'.
// This doesn't work either, the CEditText line does not clear.
EditText ToDo = binding16.CEditText;
// working code before ViewBinding
**strong text**EditText ToDo = getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.CEditText);
ToDo.setText(null);
// Move the focus back the CEditText line on the fully cleared skycard,
// ready again for input.
getActivity().findViewById(R.id.CEditText).requestFocus();
}
}
}
}
My suggestion is to avoid to get reference of activity's widgets (CEditText in your case) from the dialog fragment itself and use an interface to signal back the activity which click action has been done and act upon that.
You can do for instance:
public class SkycardClearFragment extends DialogFragment {
private DialogCallbacks callbacks;
public SkycardClearFragment(DialogCallbacks callbacks) {
this.callbacks = callbacks;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceSate) {
Button btnClearOK = binding15.btnClearOK;
btnClearOK.setOnClickListener(v -> callbacks.onOkClicked());
}
interface DialogCallbacks {
void onOkClicked();
void onCancelClicked();
}
}