Home > OS >  How to pass custom objects from an activity to a fragment?
How to pass custom objects from an activity to a fragment?

Time:04-10

I've been searching all day and couldn't find a real answer. I created a fragment using the correct way, that is with a no-args constructor and using Fragment setArguments(Bundle) to pass data to it.

I need to pass a Drawable and another custom object to the fragment. Everything I read talks about passing the integer ID of the drawable instead of the drawable object. But the drawable I'm passing doesn't have an ID, it's from an array of drawables that includes all the icons of the user's installed apps, and this array was already loaded beforehand. I just want to pass the drawable without having to recreate anything inside the fragment. Is this possible?

CodePudding user response:

You can do something like this:
Your activity:

public class YourActivity extends AppCompatActivity {

    ...
    public Drawable drawableToGet; //Here is the drawable you want to get
    ...

}

In your Fragment:

public Drawable getDrawableFromActivity(){
    Activity activity = getActivity();
    if(activity instanceof YourActivity){
        return ((YourActivity) activity).drawableToGet;
    } else {
        //Fragment isn't attached to YourActivity
        return null;
    }
}
  • Related