How do I pass parameters from the last Fragment to the previous Fragment?

4

I have the following situation: Fragment A is opened and it, with a click event, goes to Fragment B . When in Fragment B and pressing the back button, in order to return to Fragment A , I would like to pass some parameters to Fragment A . Does anyone know how I can do this?

    
asked by anonymous 04.04.2014 / 22:24

2 answers

2

One of the ways to do this is to have Activities talk to each other and that Fragments can communicate with Activities or with each other through them. Here is a description of the two portions that would need to be implemented.

Between Activities

The most common scenario (which appears to be yours) is when a child activity is started to collect user responses - such as picking a ciontato from a list or entering text. In this case you should use startActivityForResult to start your child activity.

This provides a means to send data back to the parent (parent) activity using the setResult method. This method uses a int as a value for the result and a Intent is passed back to the activity that called it.

Intent resultado = new Intent();
// Adicione extras ou uma URI de dados para esta intent como apropriado.
setResult(Activity.RESULT_OK, resultado);
finish();

To access the data returned by the child activity, overwrite ( override ) the onActivityResult method. The requestCode corresponds to the int passed in the call startActivityForResult , while the resultCode and the Intent data are returned by the child activity.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (ATIVIDADE_FILHA) : {
      if (resultCode == Activity.RESULT_OK) {
        // Extraia os dados retornados pela atividade filha.
      }
      break;
    } 
  }
}

Between Fragments

To make Fragments talk to each other, you must first create an interface for it, and Activities of Fragments must implement this interface. Then the Activities can talk to each other through the technique shown above.

In your% of% Person you need to create the interface that will be used and call the callback in the appropriate events (of your choice).

public class PessoaFragment extends Fragment {
    OnSettingsListener mCallback;

    // A Activity que contém o fragment deve implementar esta interface
    public interface OnSettingsListener {
        public void OnSettingsDone(int data);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // Este código serve para nos certificarmos que a Activity que contém o Fragment
        // implementa a interface do callback. Se não, lança uma exceção
        try {
            mCallback = (OnSettingsListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " precisa implementar OnSettingsListener");
        }
    }

    ...

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Envia o evento para a Activity que chamou
        mCallback.OnSettingsDone(position);
    }

}

In% of parent or parent%, which I'll call Fragment , you need to implement the interface and make proper communication.

public static class MainActivity extends Activity
    implements PessoaFragment.OnSettingsListener{
...

    public void OnSettingsDone(int position) {
        // O usuário selecionou uma posição da configuração

        PessoaFragment pessoaFrag = (PessoaFragment)
                getSupportFragmentManager().findFragmentById(R.id.pessoa_fragment);

        if (pessoaFrag != null) {
            // Se o fragment da pessoa está disponível, estamos num layout de dois painéis (num tablet)

            //Chama um método para atualziar o conteúdo
            pessoaFrag.atualizaConfiguracao(position);
        } else {
            // Se não, estamos num layout de um painel apenas e precisamos trocar os fragments...

            // Cria um fragment e passa para ele como parâmetro as configurações selecionadas
            PessoaFragment newFragment = new PessoaFragment();
            Bundle args = new Bundle();
            args.putInt(PessoaFragment.ARG_POSITION, position);
            newFragment.setArguments(args);

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Troca o que quer que tenha na view do fragment_container por este fragment,
            // e adiciona a transação novamente na pilha de navegação
            transaction.replace(R.id.content_frame, newFragment);
            transaction.addToBackStack("pilha");

            // Finaliza a transção com sucesso
            transaction.commit();
        }
    }
}
    
05.04.2014 / 00:48
0

I solved this in a simple way for something simple. In an activity Master where management the Fragments I declare a variable publish.

public class Master extends ActionBarActivity {

  public long idTeste;

And then the Fragments are set and obtained in the following ways

 Master master = (Master)getActivity();
 master.idTeste = 1;
 int id teste = master.idTeste;

So keeping the value of the variable declared in the Master and navigating between Fragments.

Another way is to create a class with static properties.

Now, if both ways are good practices for programming, I do not know.

    
09.04.2014 / 16:29