AKTStudios
AKTStudios

Reputation: 105

get resource from a fragment

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.

Upvotes: 5

Views: 23673

Answers (3)

LionKing
LionKing

Reputation: 723

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;
}

Upvotes: 0

Simon
Simon

Reputation: 2419

I got this working in a fragment:

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

Upvotes: 9

Kevin
Kevin

Reputation: 2585

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.

Upvotes: 1

Related Questions