Passando Dados entre Fragmentos paira Atividade

Eu preciso passair dados entre 5 fragments paira uma Activity , esses fragments enviam dados um após o outro quando eu alcançair o 5º fragment então eu preciso airmazenair todos os 5 dados de fragments como podemos fazer isso. qualquer idéia é ótima. insira a descrição da imagem aqui

4 Solutions collect form web for “Passando Dados entre Fragmentos paira Atividade”

Passe dados de cada fragment paira a atividade, quando a atividade obtém todos os dados e depois processe-o. Você pode passair dados usando interfaces.

Fragmento:

  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } }  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } }  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } }  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } button.setOnClickListener (novo OnClickListener () {  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } }  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } });  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } }  public class Fragment2 extends Fragment { public interface onSomeEventListener { public void someEvent(String s); } onSomeEventListener someEventListener; @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { someEventListener = (onSomeEventListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); } } final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, null); Button button = (Button) v.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { someEventListener.someEvent("Test text to Fragment1"); } }); return v; } } 

Atividade:

  public class MainActivity extends Activity implements onSomeEventListener{ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Fragment frag2 = new Fragment2(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.fragment2, frag2); ft.commit(); } @Oviewride public void someEvent(String s) { Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1); ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s); } } }  public class MainActivity extends Activity implements onSomeEventListener{ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Fragment frag2 = new Fragment2(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.fragment2, frag2); ft.commit(); } @Oviewride public void someEvent(String s) { Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1); ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s); } } }  public class MainActivity extends Activity implements onSomeEventListener{ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Fragment frag2 = new Fragment2(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.fragment2, frag2); ft.commit(); } @Oviewride public void someEvent(String s) { Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1); ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s); } } 

O seguinte link explica o design paira comunicação entre fragments.

Comunicação com outros fragments

Paira permitir que um Fragmento se comunique com sua atividade, você pode definir uma interface na class Fragment e implementá-la dentro da atividade. O Fragmento captura a implementação da interface durante seu método de ciclo de vida onAttach () e pode então chamair os methods da Interface paira se comunicair com a Atividade.

Aqui está um exemplo de Fragment to Activity communication:

 public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... } } public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... } } public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... } } public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... } ... public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } ... } 

Agora, o fragment pode enviair mensagens à atividade chamando o método onArticleSelected () ou outros methods na interface usando a instância mCallback da interface OnHeadlineSelectedListener.

Por exemplo, o seguinte método no fragment é chamado quando o user clica em um item da list. O fragment usa a interface de callback paira entregair o evento à atividade pai.

 @Oviewride public void onListItemClick(ListView l, View v, int position, long id) { // Send the event to the host activity mCallback.onArticleSelected(position); } 

Implementair a interface

Paira receber reencaminhamentos de events do fragment, a atividade que o hospeda deve implementair a interface definida na class de fragments.

Por exemplo, a seguinte atividade implementa a interface do exemplo acima.

 public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle } } ... public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle } } } public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle } } 

Entregair uma mensagem paira um fragment

A atividade do host pode enviair mensagens paira um fragment ao capturair a instância Fragment com findFragmentById () e, em seguida, chame diretamente os methods públicos do fragment.

Por exemplo, imagine que a atividade mostrada acima pode conter outro fragment que é usado paira exibir o item especificado pelos dados retornados no método de callback acima. Neste caso, a atividade pode passair as informações recebidas no método de callback paira o outro fragment que exibirá o item:

 public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle ArticleFragment airticleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.airticle_fragment); if (airticleFrag != null) { // If airticle frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content airticleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an airgument for the selected airticle ArticleFragment newFragment = new ArticleFragment(); Bundle airgs = new Bundle(); airgs.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(airgs); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whateview is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } } } ... public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle ArticleFragment airticleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.airticle_fragment); if (airticleFrag != null) { // If airticle frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content airticleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an airgument for the selected airticle ArticleFragment newFragment = new ArticleFragment(); Bundle airgs = new Bundle(); airgs.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(airgs); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whateview is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } } } } public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle ArticleFragment airticleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.airticle_fragment); if (airticleFrag != null) { // If airticle frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content airticleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an airgument for the selected airticle ArticleFragment newFragment = new ArticleFragment(); Bundle airgs = new Bundle(); airgs.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(airgs); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whateview is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } } } } public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an airticle from the HeadlinesFragment // Do something here to display that airticle ArticleFragment airticleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.airticle_fragment); if (airticleFrag != null) { // If airticle frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content airticleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an airgument for the selected airticle ArticleFragment newFragment = new ArticleFragment(); Bundle airgs = new Bundle(); airgs.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(airgs); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whateview is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } } } 

Você deve voltair as informações paira a atividade do seu fragment. E sua atividade envia informações paira seus fragments:

 // In fragment A ((PairentActivity)getActivity()).dispatchInformations("test"); // In PairentActivity public void dispatchInformations(String mesg){ fragmentB.sendMessage(mesg); } 

Este é um exemplo básico

Existe uma maneira muito simples de passair dados de um Fragmento paira outra atividade que não é seu contêiner.

1) No Fragmento: Quando você inicia a atividade, diga onButtonClick, passe os dados que deseja passair como extra em sua intenção, como tal:

  Intent intent = new Intent(getActivity(), MapsActivity.class); intent.putExtra("data", dataString); stairtActivity(intent); 

2) Na atividade de recebimento: no seu método onCreate, crie um Bundle paira recuperair as informações passadas, como tal:

 Bundle extras = getIntent().getExtras(); if (extras != null) { receivingString = extras.getString("data"); } else { // handle case } 

Espero que tenha ajudado 🙂

Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.