Send data to fragment with FragmentTransaction

16,156

Solution 1

Just pass them in a bundle as fragment arguments

in parent fragment :

SettingsBlockedUsersFragment fragment = new SettingsBlockedUsersFragment();
Bundle arguments = new Bundle();
arguments.putString( string_key , desired_string);
fragment.setArguments(arguments);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, fragment , FRAGMENT_TAG);
ft.commit();

in child fragment :

Bundle arguments = getArguments();
String desired_string = arguments.getString(string_key);

Solution 2

FragmentTransaction is simply to transition Fragments, it doesn't "pass" anything. You need to use a Bundle.

SettingsBlockedUsersFragment frag = new SettingsBlockedUsersFragment();
Bundle b = new Bundle();
// put stuff into bundle...
b.putString("user", "steve");

// Pass the bundle to the Fragment
frag.setArguments(b);

// Use Fragment Transaction
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, frag, FRAGMENT_TAG);
ft.commit();

Then inside the onCreate of the Fragment, you can do

String user = getArguments().getString("user");

Other ways to pass data into a Fragment are discussed at Best practice for instantiating a new Android Fragment

Share:
16,156
y07k2
Author by

y07k2

BY DAY: Java Developer at work. Android Developer at home. BY NIGHT: I'm interested in sport (especially football), new technologies and mobile phones. FOR FUN: Playing FIFA 17 with friends, watching football matches (EPL, UCL and Polish Ekstraklasa) and play football with mates.

Updated on July 21, 2022

Comments

  • y07k2
    y07k2 almost 2 years

    I'm in my fragment class calling this:

    @OnClick(R.id.blockedLinkLayout)
    public void onBlockedClick(){
        final FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.content, new SettingsBlockedUsersFragment(), FRAGMENT_TAG);
        ft.commit();
    }
    

    And it just replace my current fragment with chosen one.

    And my question is, how can I send some data (e.g. String value) from my parent fragment to my child fragment using FragmentTransaction?

  • kandroidj
    kandroidj about 8 years
    I think you mean to say FragmentTransaction not FragmentTransition
  • y07k2
    y07k2 about 8 years
    It works! What if I want to send e.g. HashMap oraz ArrayList?
  • Mohsen fallahi
    Mohsen fallahi about 8 years
    you could use arguments.putStringArrayList(key, value); . note that bundle is limited to simple values like String or int .
  • y07k2
    y07k2 about 8 years
    So I need to change Bundle type to what?
  • Mohsen fallahi
    Mohsen fallahi about 8 years
    just use arguments.putStringArrayList("my_array", the_string_array); ;) you don't have to do anything else