Search code examples
androidandroid-fragmentsandroidx

SetBackground for button in Fragment with androidx showing warning: argument getActivity() might be null


Trying to change button background color in Fragment but giving the following warning. I am using androidx in Android Studio version 4.0.1

argument getActivity() might be null

Fragment Function

public class ProfileFragment extends Fragment {

    ...

    private void setButtonIcon(Button button, Integer drawable) {

        button.setBackground(ContextCompat.getDrawable(getActivity(), drawable));

    }
}

Solution

  • According to documentation, we can try with requireActivity() or requireContext()

    requireActivity() Return the FragmentActivity this fragment is currently associated with.

    requireContext() Return the Context this fragment is currently associated with.

    In the code side, they already checked like below

     if (activity == null) {
                throw new IllegalStateException("Fragment " + this + " not attached to an activity.");
            }
    
     if (context == null) {
                throw new IllegalStateException("Fragment " + this + " not attached to a context.");
            }
    

    IDE won't show warning if we used those instead of getActivity() or getContext().