我正在尝试在片段中更改 android 中 ImageButton 的来源。
我想使用 Image.setImageResource() 方法,但是我不能在片段中使用 getResources() 。有办法解决这个问题吗?getActivity().getResources() 不幸地没有返回任何结果。
我试过写一个字符串,比如“R.drawable”。+ {不同的图像名称},但我无法将该字符串转换为 int。
这还能怎么做?
我只想用依赖于不同事物的源文件更改一些 imageButtons。
我正在尝试在片段中更改 android 中 ImageButton 的来源。
我想使用 Image.setImageResource() 方法,但是我不能在片段中使用 getResources() 。有办法解决这个问题吗?getActivity().getResources() 不幸地没有返回任何结果。
我试过写一个字符串,比如“R.drawable”。+ {不同的图像名称},但我无法将该字符串转换为 int。
这还能怎么做?
我只想用依赖于不同事物的源文件更改一些 imageButtons。
我在一个片段中得到了这个工作:
int imageresource = getResources().getIdentifier("@drawable/your_image", "drawable", getActivity().getPackageName());
image.setImageResource(imageresource);
R.drawable.imagename是一个整数。并setImageResource()接受一个 int:
imageButton.setImageResource(R.drawable.imagename)
另外,getActivity().getResources()什么都不返回也很奇怪。如果您的 Fragment 附加到 Activity,则应该返回一个 Resources 对象。
我们可以在 onCreateView(...) 方法中使用资源:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_name, container, false);
int sizeView = rootView.getResources().getDimension(R.dimen.size_view));
return view;
}