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();
}
}
}