domingo, 8 de diciembre de 2013

Android: Passing data to a fragment through its Arguments

To pass data to a fragment through its arguments you need to do the following steps:

1 - Create a Bundle object.
2 - Populate the Bundle object with the desired data. If the data to be passed is a custom class you need to make that class implement Parceable or pass all the data you need to recreate that object in the fragment (not recommended). See this post.
3 - Create the fragment and add the bundle object to the fragment's argument with the setArguments method. The first argument of this method is a key in the form of a String. Usually this key String will be a constant defined in the fragment class.
4 - In the fragment class in the onCreate method you need to take the bundle object from the arguments and what you please with it.

Example. Let's suppose I have a list of people and when the user clicks on one the Person object will be passed to a fragment for it to display.

public class Person implements Parcelable {
...

}

public class PeopleListActivity extends FragmentActivity {

private ListView list;
private FrameLayout fragmentContainer;

@Override
protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  this.setContentView(R.layout.activity_people_list);

  fragmentContainer = 
    (FrameLayout) this.findViewById(R.id.fragment_container);

  PersonAdapter adapter = new PersonAdapter();

  list = (ListView) this.findViewById(R.id.listview);
  list.setAdapter(adapter);
  list.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {

    Bundle arguments = new Bundle();
    arguments.putParcelable(PersonDetailFragment.PERSON, person);

    PersonDetailFragment fragment = new PersonDetailFragment();

    fragment.setArguments(arguments);

    getSupportFragmentManager().beginTransaction()
      .add(R.id.fragment_container, fragment).commit();
  }
});

}


public class PersonDetailFragment extends Fragment {

public static final String PERSON =              
  "com.example.PersonList.PersonDetailFragment.PERSON";

...

@Override
public void onCreate(Bundle savedInstanceState) {
   
  super.onCreate(savedInstanceState);
        
  Parcelable person = (Person) this.getArguments().getParcelable(PERSON);
        
  ...
}

}

No hay comentarios:

Publicar un comentario