为片段中的按钮设置背景,androidx 显示警告:参数 getActivity() 可能为空
SetBackground for button in Fragment with androidx showing warning: argument getActivity() might be null
正在尝试更改 Fragment
中的按钮背景颜色,但出现以下警告。我在 Android Studio 版本 4.0.1
中使用 androidx
argument getActivity() might be null
片段函数
public class ProfileFragment extends Fragment {
...
private void setButtonIcon(Button button, Integer drawable) {
button.setBackground(ContextCompat.getDrawable(getActivity(), drawable));
}
}
根据文档,我们可以尝试使用 requireActivity() 或 requireContext()
requireActivity() Return the FragmentActivity this fragment is
currently associated with.
requireContext() Return the Context this fragment is currently
associated with.
在代码方面,他们已经检查如下
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.");
}
如果我们使用它们而不是 getActivity() 或 getContext(),IDE 将不会显示警告。
正在尝试更改 Fragment
中的按钮背景颜色,但出现以下警告。我在 Android Studio 版本 4.0.1
androidx
argument getActivity() might be null
片段函数
public class ProfileFragment extends Fragment {
...
private void setButtonIcon(Button button, Integer drawable) {
button.setBackground(ContextCompat.getDrawable(getActivity(), drawable));
}
}
根据文档,我们可以尝试使用 requireActivity() 或 requireContext()
requireActivity() Return the FragmentActivity this fragment is currently associated with.
requireContext() Return the Context this fragment is currently associated with.
在代码方面,他们已经检查如下
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.");
}
如果我们使用它们而不是 getActivity() 或 getContext(),IDE 将不会显示警告。