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

Asked

Viewed 4,107 times

4

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

2 answers

2


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


Amid Activities

The most common scenario (which seems to be yours) is when a daughter activity is started to gather user responses - such as choosing an ciontato from a list or typing a text. In this case you should use startActivityForResult to start your daughter activity.

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

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 overwrite daughter activity (make a override) the method onActivityResult. The requestCode corresponds to the int past call startActivityForResult, as long as the resultCode and the data of Intent are returned by daughter 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;
    } 
  }
}

Amid Fragments

To make the Fragments talk to each other you need to create an interface for this and the Activities of Fragments need to implement this interface. Done this Activities can converse with each other through the previously demonstrated technique.

In his Fragment Person you need to create the interface that will be used and call the callback at the appropriate events (at 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 the Activity mother or principal, which I will call Main, you need to implement the interface and make the 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();
        }
    }
}
  • Right. I’m grateful for the answer. I used it to work with Activity, but I do not think it is applicable in this way in the use of Fragments due to the use of consecutive transactions. Could you tell me about this or something with transactions in Fragments?

  • I’ll take a look. How are you starting the Fragments at the moment? You should have a Activity related to each Fragment or at least one main that manages all Fragments, right?

  • Yes I have a Activity that manages all the Fragments. I’ll put the code here.

  • FragmentTransaction fragmentTransaction;


Fragment currentFragment = new PessoaFragment();


FragmentManager fragmentManager = getFragmentManager();


fragmentTransaction = fragmentManager.beginTransaction().
replace(R.id.content_frame, currentFragment, "tagConfigPessoas");



fragmentTransaction.addToBackStack("pilha");


fragmentTransaction.commit();

  • @Ferzinhafil takes a look at the update I made commenting on the communication between the Fragments.

  • Nossaa, thank you @Alexandremarcondes . I will use this logic in my application. It has clarified many of my doubts, thank you very much. Congratulations on your willingness and explanation. Kisses. Thank you very much.

Show 1 more comment

0

This I solved in a simple way for something simple. In an Activity Master where I manage the Fragments I declare a public variable.

public class Master extends ActionBarActivity {

  public long idTeste;

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

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

Thus maintaining the value of the variable declared in Master and navigating between Fragments.

Another way is to create a class with static properties.

Now, if the two ways are good practice programming, I don’t know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.