Get resource from fragment

I am trying to change the ImageButton source in android inside a fragment.

I want to use the Image.setImageResource () method, however I cannot use getResources () inside the fragment. is there any way around this? getActivity (). getResources () does not return any results, unfortunately.

I tried writing a string such as "R.drawable". + {different image names}, but I cannot convert this string to int.

How else can this be done?

I just want to change some image buttons with source files depending on different things.

+4
source share
3 answers

I got this work in a snippet:

int imageresource = getResources().getIdentifier("@drawable/your_image", "drawable", getActivity().getPackageName()); image.setImageResource(imageresource); 
+7
source

R.drawable.imagename is an int. And setImageResource() takes an int:

imageButton.setImageResource(R.drawable.imagename)

It is also strange that getActivity().getResources() will not return anything. If your fragment is bound to an Activity, it should return a Resources object.

+1
source

We can use the resources in the onCreateView (...) method:

 @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; } 
0
source

Source: https://habr.com/ru/post/1492480/


All Articles