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 ofFragments
due to the use of consecutive transactions. Could you tell me about this or something with transactions inFragments
?– Ferzinha Fil
I’ll take a look. How are you starting the Fragments at the moment? You should have a
Activity
related to eachFragment
or at least one main that manages allFragments
, right?– Alexandre Marcondes
Yes I have a
Activity
that manages all theFragments
. I’ll put the code here.– Ferzinha Fil
FragmentTransaction fragmentTransaction;


Fragment currentFragment = new PessoaFragment();


FragmentManager fragmentManager = getFragmentManager();


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



fragmentTransaction.addToBackStack("pilha");


fragmentTransaction.commit();
– Ferzinha Fil
@Ferzinhafil takes a look at the update I made commenting on the communication between the Fragments.
– Alexandre Marcondes
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.
– Ferzinha Fil