在Android片段中初始化Drawable图片

问题描述 投票:1回答:2

我有两张图片,我想将其作为背景图像在Android应用程序中作为片段旋转。

现在,一个静态地在.xml中为

android:background="@drawable/background"

我正在尝试初始化Fragment.java中的两张照片,但出现空指针错误。

private Drawable img1 =
ContextCompat.getDrawable(this.getContext(),R.drawable.background);

private Drawable img2 =
ContextCompat.getDrawable(this.getContext(),R.drawable.background2);

有人对我为什么在这里出现空错误有任何建议吗?

谢谢!

android android-drawable
2个回答
0
投票

您可能想要getActivity()而不是getContext()getContext是在API 23中添加的,如果在以前的版本中调用,我认为会导致NPE。


0
投票

在onCreateView中调用它,而不是直接分配值。它将解决您的问题。

private Drawable deleteIcon;公共视图onCreateView(LayoutInflater充气机,ViewGroup容器,捆绑保存的InstanceState){deleteIcon = ContextCompat.getDrawable(getContext(),R.drawable.ic_delete_black_24dp);}

© www.soinside.com 2019 - 2024. All rights reserved.