5

I'm trying to change the source of an ImageButton in android within a fragment.

I want to use the method Image.setImageResource() , however i can't use getResources() within the fragment. is there a way round this? getActivity().getResources() does not return any results unfortuantely.

I've tried writing a string such as "R.drawable." + {different image names} but i cannot convert that string to an int.

How else could this be done?

I just want to change some imageButtons with source files dependent on different things.

AKTStudios
  • 105
  • 1
  • 3
  • 10

3 Answers3

9

I got this working in a fragment:

int imageresource = getResources().getIdentifier("@drawable/your_image", "drawable", getActivity().getPackageName());        
    image.setImageResource(imageresource);
Simon
  • 2,328
  • 6
  • 26
  • 30
  • Also we can use resources from xml. for example getActivity().getResources().getColor(R.color.rose) – Parthi Jan 19 '15 at 09:00
1

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

imageButton.setImageResource(R.drawable.imagename)

Also, it's strange that getActivity().getResources() would return nothing. If your Fragment is attached to an Activity, that should return a Resources object.

Kevin
  • 2,605
  • 2
  • 20
  • 15
  • @AKTStudios `getActivity().getResources()` should work since `getResources` requires activity context. Post your implementation. – Raghunandan Jul 20 '13 at 16:12
  • @user1380611 Hi all, Thanks for your answers it turns out the methods were working properly... and strangely only after i restarted eclipse did it find that the getResources() method was accessible locally... strange that. incidentally i got the image loading to work as i forgot to put in the "@drawable/" - Thanks user1380611. Working now :-) – AKTStudios Jul 20 '13 at 18:50
  • I'm glad to hear that, you could set it as answer – Simon Jul 20 '13 at 18:51
0

We can use resources in 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;
}
LionKing
  • 725
  • 8
  • 8