Search code examples
androidandroid-fragmentsandroid-intentextras

Can you give extras to a Fragment on replace?


I currently have an app that relies heavily on Intents and the extras given to them before starting the activity. The extras are used when calling a webservice which in turn supplies the content that needs to be shown

I am trying to convert that model, to one where I have a static Fragment (lets call it Player) at the bottom of my screen, and another Fragment (lets call it Content) above it which will show the main content. By selecting options on the main screen other content will be shown by replacing the Content Fragment.

But, these new Fragments are currently the Intents that rely on the extras so heavily. Is there a way to replace a Fragment by a new one, but still be able to add extras to it?

If so, let's say I have the following piece of code:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_holder, new MusicAlbumList(), "albumlist");
        ft.commit();

How would I add the extras to the MusicAlbumList?

If that's not possible, how will I get the data that's currently being passed through extras into my new Fragment before it force closes due to missing essential data?


Solution

  • Or you can do this

    MusicAlbumList fragment = new MusicAlbumList();
    Bundle args = new Bundle();
    args.putString("StringName","Value here");
    fragment.setArguments(args);
    

    then do your replace stuff. Then in the fragments onStart or onCreate call this.getArguments(); to pull the bundle, then get your extras out of there.