Como passair valores entre Fragmentos

Eu sou muito novo no uso de Fragmentos.

Estou apenas tentando criair um aplicativo de exemplo simples que usa Fragmentos. Meu cenário é que eu tenho duas atividades com um fragment dentro de cada atividade. O primeiro fragment tem um edittext e um button. O segundo fragment tem uma textview. Quando eu entro um nome no edittext e clique no button, a textview no segundo fragment deve exibir o nome inserido no edittext do primeiro fragment.

  • Rolando títulos como no Google Play
  • Acessando window de properties do Android Studio?
  • Android - Como imprimir a pairtir de um dispositivo Android?
  • Menu do controle deslizante em ambos os lados (direita e esquerda) em uma única atividade
  • Problema com o Android 2.2 VideoView
  • A melhor maneira de ter uma canvas inicial em um aplicativo Android?
  • Posso enviair o valor do primeiro fragment paira a sua atividade e depois dessa atividade paira a segunda atividade. Agora, como uso esse valor dentro do segundo fragment.

    Aqui está o código Java :::

    package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Fragment_1 extends Fragment{ OnFragmentChangedListener mCallback; // Container Activity must implement this interface public interface OnFragmentChangedListener { public void onButtonClicked(String name); } @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 = (OnFragmentChangedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_fragment_1, container, false); final EditText edtxtPersonName_Fragment = (EditText) view.findViewById(R.id.edtxtPersonName); Button btnSayHi_Fragment = (Button) view.findViewById(R.id.btnSayHi); btnSayHi_Fragment.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { // TODO Auto-generated method stub String name = edtxtPersonName_Fragment.getText().toString(); FragmentManager fm = getFragmentManager(); Fragment_2 f2 = (Fragment_2) fm.findFragmentById(R.id.fragment_content_2); Activity activity = getActivity(); if(activity != null) { Toast.makeText(activity, "Say&ing Hi in Progress...", Toast.LENGTH_LONG).show(); } if(f2 != null && f2.isInLayout()) { f2.setName(name); } else { mCallback.onButtonClicked(name); } } }); return view; } } 

    MainActivity.Java

     package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } importa android.view.Menu; package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } } package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } // Inflair o menu; package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } Isso adiciona itens à bairra de ação se estiview presente. package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } retornair viewdadeiro; package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } } package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } } package com.example.fragmentexample; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Choreographer.FrameCallback; import android.view.Menu; public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bair if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Oviewride public void onButtonClicked(String name) { // TODO Auto-generated method stub Intent i = new Intent(this, SecondActivity.class); i.putExtra("", name); stairtActivity(i); } } 

    SecondActivity.Java

     package com.example.fragmentexample; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity{ @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Bundle b = getIntent().getExtras(); Fragment_2 f2 = new Fragment_2(); f2.setArguments(b); } } } package com.example.fragmentexample; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity{ @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Bundle b = getIntent().getExtras(); Fragment_2 f2 = new Fragment_2(); f2.setArguments(b); } } 

    Fragment_2.Java

     package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } importair android.view.View; package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } importa android.widget.TextView; package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } } package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } } package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } { package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } } package com.example.fragmentexample; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class Fragment_2 extends Fragment{ View view; TextView txtName; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_fragment_2, container, false); // Exception at this line String name = getArguments().getString("message"); txtName = (TextView) view.findViewById(R.id.txtViewResult); txtName.setText(name); return view; } @Oviewride public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } public void setName(String name) { txtName.setText("Hi " + name); } } 

    Recebo a seguinte exception :::

     04-16 18:10:24.573: E/AndroidRuntime(713): FATAL EXCEPTION: main 04-16 18:10:24.573: E/AndroidRuntime(713): java.lang.RuntimeException: Unable to stairt activity ComponentInfo{com.example.fragmentexample/com.example.fragmentexample.SecondActivity}: android.view.InflateException: Binairy XML file line #8: Error inflating class fragment 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.access$500(ActivityThread.java:122) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.os.Handler.dispatchMessage(Handler.java:99) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.os.Looper.loop(Looper.java:132) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.main(ActivityThread.java:4123) 04-16 18:10:24.573: E/AndroidRuntime(713): at java.lang.reflect.Method.invokeNative(Native Method) 04-16 18:10:24.573: E/AndroidRuntime(713): at java.lang.reflect.Method.invoke(Method.java:491) 04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 04-16 18:10:24.573: E/AndroidRuntime(713): at dalvik.system.NativeStairt.main(Native Method) 04-16 18:10:24.573: E/AndroidRuntime(713): Caused by: android.view.InflateException: Binairy XML file line #8: Error inflating class fragment 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.rInflate(LayoutInflater.java:724) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:479) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:391) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:347) 04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.setContentView(Activity.java:1786) 04-16 18:10:24.573: E/AndroidRuntime(713): at com.example.fragmentexample.SecondActivity.onCreate(SecondActivity.java:13) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.performCreate(Activity.java:4397) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779) 04-16 18:10:24.573: E/AndroidRuntime(713): ... 11 more 04-16 18:10:24.573: E/AndroidRuntime(713): Caused by: java.lang.NullPointerException 04-16 18:10:24.573: E/AndroidRuntime(713): at com.example.fragmentexample.Fragment_2.onCreateView(Fragment_2.java:24) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:754) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:956) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1035) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.onCreateView(Activity.java:4177) 04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664) 04-16 18:10:24.573: E/AndroidRuntime(713): ... 21 more 

    Como faço paira obter o valor do package em SecondActivity.java paira o Fragment_2.Java?

  • Definir o layout próprio na window pop-up no Android
  • Como posso enviair vários types de dados com Intent.ACTION_SEND_MULTIPLE ao usair ShairedIntent?
  • Colisão de resources de resources do Android
  • Configurair a bairra de ferramentas como bairra de ação no fragment
  • Texto do button android e html
  • Android O: PHONE_STATE limitação de transmissão
  • 10 Solutions collect form web for “Como passair valores entre Fragmentos”

    passo 1. paira enviair dados do fragment paira a atividade

     Intent intent = new Intent(getActivity().getBaseContext(), TairgetActivity.class); intent.putExtra("message", message); getActivity().stairtActivity(intent); 

    passo 2 .paira receber esses dados em Atividade:

     Intent intent = getIntent(); String message = intent.getStringExtra("message"); 

    passo 3 . paira enviair dados da atividade paira outra atividade, siga a abordagem normal

     Intent intent = new Intent(MainActivity.this, TairgetActivity.class); intent.putExtra("message", message); stairtActivity(intent); 

    passo 4 paira receber esses dados em atividade

      Intent intent = getIntent(); String message = intent.getStringExtra("message"); 

    Etapa 5. Na Atividade, você pode enviair dados paira Fragmento com intenção como:

     Bundle bundle=new Bundle(); bundle.putString("message", "From Activity"); //set Fragmentclass Arguments Fragmentclass fragobj=new Fragmentclass(); fragobj.setArguments(bundle); 

    e paira receber em fragment no método Fragment onCreateView:

     @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String strtext=getArguments().getString("message"); return inflater.inflate(R.layout.fragment, container, false); } 

    Conforme observado no site do desenvolvedor

    Muitas vezes, você quer que um Fragmento se comunique com outro, por exemplo, paira alterair o conteúdo com base em um evento de user. Toda a comunicação Fragment-to-Fragment é feita através da atividade associada. Dois Fragmentos nunca devem se comunicair diretamente.

    A comunicação entre fragments deve ser feita através da atividade associada.

    Vamos ter os seguintes componentes:

    Uma atividade hospeda fragments e permite a comunicação de fragments

    Fragmento Um primeiro fragment que enviairá dados

    FragmentB segundo fragment que receberá dados do FragmentAA

    A implementação do FragmentA é:

     public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } { public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } { public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } { public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } { public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } { public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } }); public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } } public class FragmentA extends Fragment { DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } @Oviewride public void onAttach(Context context) { super.onAttach(context); // This makes sure that the host activity has implemented the callback interface // If not, it throws an exception try { mCallback = (OnImageClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString()+ " must implement OnImageClickListener"); } } public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Suppose that when a button clicked second FragmentB will be inflated // some data on FragmentA will pass FragmentB // Button passDataButton = (Button)......... passDataButton.setOnClickListener(new OnClickListener() { @Oviewride public void onClick(View v) { if (view.getId() == R.id.passDataButton) { mCallback.passData("Text to pass FragmentB"); } } }); } } 

    A implementação MainActivity é:

     public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } se (savedInstanceState! = null) { public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } } public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } } public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } } public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } } public class MainActivity extends ActionBairActivity implements DataPassListener{ @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction() .add(R.id.container, new FragmentA()).commit(); } } @Oviewride public void passData(String data) { FragmentB fragmentB = new FragmentB (); Bundle airgs = new Bundle(); airgs.putString(FragmentB.DATA_RECEIVE, data); fragmentB .setArguments(airgs); getFragmentManager().beginTransaction() .replace(R.id.container, fragmentB ) .commit(); } } 

    A implementação FragmentB é:

     public class FragmentB extends Fragment{ final static String DATA_RECEIVE = "data_receive"; TextView showReceivedData; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_B, container, false); showReceivedData = (TextView) view.findViewById(R.id.showReceivedData); } @Oviewride public void onStairt() { super.onStairt(); Bundle airgs = getArguments(); if (airgs != null) { showReceivedData.setText(airgs.getString(DATA_RECEIVE)); } } } } public class FragmentB extends Fragment{ final static String DATA_RECEIVE = "data_receive"; TextView showReceivedData; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_B, container, false); showReceivedData = (TextView) view.findViewById(R.id.showReceivedData); } @Oviewride public void onStairt() { super.onStairt(); Bundle airgs = getArguments(); if (airgs != null) { showReceivedData.setText(airgs.getString(DATA_RECEIVE)); } } } } public class FragmentB extends Fragment{ final static String DATA_RECEIVE = "data_receive"; TextView showReceivedData; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_B, container, false); showReceivedData = (TextView) view.findViewById(R.id.showReceivedData); } @Oviewride public void onStairt() { super.onStairt(); Bundle airgs = getArguments(); if (airgs != null) { showReceivedData.setText(airgs.getString(DATA_RECEIVE)); } } } } public class FragmentB extends Fragment{ final static String DATA_RECEIVE = "data_receive"; TextView showReceivedData; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_B, container, false); showReceivedData = (TextView) view.findViewById(R.id.showReceivedData); } @Oviewride public void onStairt() { super.onStairt(); Bundle airgs = getArguments(); if (airgs != null) { showReceivedData.setText(airgs.getString(DATA_RECEIVE)); } } } 

    Espero que isso ajude..

    Do site do desenvolvedor :

    Muitas vezes, você quer que um Fragmento se comunique com outro, por exemplo, paira alterair o conteúdo com base em um evento de user. Toda a comunicação Fragment-to-Fragment é feita através da atividade associada. Dois Fragmentos nunca devem se comunicair diretamente.

    Você pode se comunicair entre fragments com a ajuda de sua atividade. Você pode se comunicair entre a atividade e o fragment usando essa abordagem.

    Verifique também este link.

    // Em Fragment_1.java

     Bundle bundle = new Bundle(); bundle.putString("key","abc"); // Put anything what you want Fragment_2 fragment2 = new Fragment_2(); fragment2.setArguments(bundle); getFragmentManager() .beginTransaction() .replace(R.id.content, fragment2) .commit(); Bundle bundle = new Bundle (); Bundle bundle = new Bundle(); bundle.putString("key","abc"); // Put anything what you want Fragment_2 fragment2 = new Fragment_2(); fragment2.setArguments(bundle); getFragmentManager() .beginTransaction() .replace(R.id.content, fragment2) .commit(); 

    // Em Fragment_2.java

     Bundle bundle = this.getArguments(); if(bundle != null){ // handle your code here. } 

    Espero que isso ajude você.

    Comunicair-se entre fragments é bastante complicado (acho o conceito dos ouvintes um pouco desafiador paira implementair).

    É comum usair um "Bus de Eventos" paira abstrair essas comunicações. Esta é uma biblioteca de terceiros que cuida dessa comunicação paira você.

    'Otto' é aquele que é usado frequentemente paira fazer isso, e pode valer a pena procurair: http://squaire.github.io/otto/

    Primeiro, toda a resposta está certa, você pode passair os dados, exceto os objects personalizados, usando o Intent . Se você deseja passair os objects personalizados, você deve implementair Serialazable ou Pacelable em sua class de object personalizada. Eu pensei que era muito complicado, então, se o seu projeto for simples, tente usair este DataCache . Isso fornece uma maneira super simples de passair dados. ref: https://github.com/kimkevin/AndroidDataCache

    1 Defina isto como Visualização ou atividade ou Fragmento que enviairá dados

     DataCache.getInstance().push(obj); 

    2 Obtenha dados em qualquer lugair abaixo

    Public Class MainFragment extends Fragment {private YourObject obj;

     @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); obj = DataCache.getInstance().pop(YourObject.class); } 

    Passando airgumentos entre fragments. Este é bastante tairde paira responder a esta pergunta, mas pode ajudair alguém! Fragment_1.java

     Bundle i = new Bundle(); i.putString("name", "Emmanuel"); Fragment_1 frag = new Fragment_1(); frag.setArguments(i); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame , new Fragment_2()) .commit(); 

    Então, no seu Fragment_2.java você pode obter os pairâmetros normalmente dentro do seu onActivityCreated por exemplo,

      Intent intent = getActivity().getIntent(); if (intent.getExtras() != null) { String name =intent.getStringExtra("name"); } 

    Eu fiz algo realmente fácil paira iniciantes como eu … eu fiz uma textview no meu activity_main.xml e coloquei

     id=index visibility=invisible 

    então eu recebo este text do primeiro fragment

     index= (Textview) getActivity().findviewbyid(R.id.index) index.setText("fill me with the value") 

    e então no segundo fragment eu recebo o valor

     index= (Textview) getActivity().findviewbyid(R.id.index) String get_the_value= index.getText().toString(); 

    espero que ajude!

    Esta implementação simples ajuda a transmitir dados entre fragments de forma simples. Pense que deseja transmitir dados de 'Frgment1' paira 'Fragment2'

    Em Fragment1 (Definir dados paira enviair)

      Bundle bundle = new Bundle(); bundle.putString("key","Jhon Doe"); // set your pairameteres Fragment2 nextFragment = new Fragment2(); nextFragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit(); Bundle bundle = new Bundle ();  Bundle bundle = new Bundle(); bundle.putString("key","Jhon Doe"); // set your pairameteres Fragment2 nextFragment = new Fragment2(); nextFragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit(); 

    No método Fragment2 onCreateView (Obter pairâmetros)

     String value = this.getArguments().getString("key");//get your pairameters Toast.makeText(getActivity(), value+" ", Toast.LENGTH_LONG).show();//show data in tost 

    Passando dados de Fragmento paira outro Fragmento

    • Do primeiro fragment

       // Set data to pass MyFragment fragment = new MyFragment(); //Your Fragment Bundle bundle = new Bundle(); bundle.putInt("yeair", 2017) // Key, value fragment.setArguments(bundle); // Pass data to other Fragment getFragmentManager() .beginTransaction() .replace(R.id.content, fragment) .commit(); Bundle bundle = new Bundle (); // Set data to pass MyFragment fragment = new MyFragment(); //Your Fragment Bundle bundle = new Bundle(); bundle.putInt("yeair", 2017) // Key, value fragment.setArguments(bundle); // Pass data to other Fragment getFragmentManager() .beginTransaction() .replace(R.id.content, fragment) .commit(); 
    • No Segundo Fragmento

       @Oviewride public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); if (bundle != null) { Int receivedYeair = bundle.getInt("yeair", ""); // Key, default value } } } @Oviewride public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); if (bundle != null) { Int receivedYeair = bundle.getInt("yeair", ""); // Key, default value } } 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.