-1

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?

  • Can you just have the `Fragment` retrieve it from the `Activity`? Put a method like `getDrawable(): Drawable` into your activity and then have the fragment call `(requireActivity() as MyActivity).getDrawable()`. – Ben P. Apr 09 '22 at 19:40
  • "it's from an array of drawables that includes all the icons of the user's installed apps" - that means you can pass the package name of the application associated with that selected icon, right? – ianhanniballake Apr 09 '22 at 19:41
  • @BenP. you mean have the activity implement an interface from the fragment? –  Apr 09 '22 at 19:49
  • @ianhanniballake yes but this would be inefficient. I don't want to access the storage for the drawable again every time the fragment gets opened. –  Apr 09 '22 at 19:51
  • Does this answer your question? [Passing an Object from an Activity to a Fragment](https://stackoverflow.com/questions/9931993/passing-an-object-from-an-activity-to-a-fragment) – Alias Cartellano Apr 09 '22 at 19:54
  • @AliasCartellano some said it's bad practice to use Serializable for anything other than small objects. –  Apr 09 '22 at 19:56
  • @AliasCartellano I also tried to convert the drawable to a json string and it crashed. –  Apr 09 '22 at 19:58
  • 1
    You still need your fragment to reload the drawable from scratch after a config change or process death and recreation. – ianhanniballake Apr 09 '22 at 20:13

1 Answers1

0

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;
    }
}
Jan Rozenbajgier
  • 534
  • 4
  • 13