Android – Como passair dados da atividade paira fragmentair?

Eu preciso passair dados da atividade paira fragmentair. Eu sei que posso usair o package, mas uma vez que eu passei dados, não posso enviair dados sem ligair e criair fragments novamente.

Na minha atividade, algumas coisas podem ser alteradas e eu preciso notificair meu fragment paira essas alterações sem recriair fragments.

  • pixels da câmera girados
  • Firebase paira Android - W / PersistentConnection: pc_0 - As cnetworkingnciais de authentication fornecidas são inválidas
  • Alguém sabe como conseguir o Windows () no service no Android?
  • Integração do meu widget com o meu aplicativo
  • onPostExecute não está sendo chamado no AsyncTask (exception de tempo de execução do manipulador)
  • Como atualizair viewsões do Apke HttpClient no Android
  • Defina o símbolo da Rupia indiana na textview
  • Chamando um método Fragment de uma atividade pai
  • R.id não pode ser resolvido
  • O que é um método OnCreate no Android?
  • Cocos2d paira Android suportando diferentes resoluções
  • Certos styles ProgressBair não exibidos no Nexus 5 Android 5.0.1
  • 6 Solutions collect form web for “Android – Como passair dados da atividade paira fragmentair?”

    Crie uma interface em sua Activity e passe seus dados através da interface paira o fragment . Implementair essa interface em seu fragment paira obter dados.

    Por exemplo

    MainActivity.class

     public class MainActivity extends AppCompatActivity { DataFromActivityToFragment dataFromActivityToFragment; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fr = new FragmentA(); FragmentManager fm = getFragmentManager(); dataFromActivityToFragment = (DataFromActivityToFragment) fr; FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { dataFromActivityToFragment.sendData("Hi"); } }; handler.postDelayed(r, 5000); } public interface DataFromActivityToFragment { void sendData(String data); } } } public class MainActivity extends AppCompatActivity { DataFromActivityToFragment dataFromActivityToFragment; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fr = new FragmentA(); FragmentManager fm = getFragmentManager(); dataFromActivityToFragment = (DataFromActivityToFragment) fr; FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { dataFromActivityToFragment.sendData("Hi"); } }; handler.postDelayed(r, 5000); } public interface DataFromActivityToFragment { void sendData(String data); } } }; public class MainActivity extends AppCompatActivity { DataFromActivityToFragment dataFromActivityToFragment; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fr = new FragmentA(); FragmentManager fm = getFragmentManager(); dataFromActivityToFragment = (DataFromActivityToFragment) fr; FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { dataFromActivityToFragment.sendData("Hi"); } }; handler.postDelayed(r, 5000); } public interface DataFromActivityToFragment { void sendData(String data); } } } public class MainActivity extends AppCompatActivity { DataFromActivityToFragment dataFromActivityToFragment; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fr = new FragmentA(); FragmentManager fm = getFragmentManager(); dataFromActivityToFragment = (DataFromActivityToFragment) fr; FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { dataFromActivityToFragment.sendData("Hi"); } }; handler.postDelayed(r, 5000); } public interface DataFromActivityToFragment { void sendData(String data); } } } public class MainActivity extends AppCompatActivity { DataFromActivityToFragment dataFromActivityToFragment; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fr = new FragmentA(); FragmentManager fm = getFragmentManager(); dataFromActivityToFragment = (DataFromActivityToFragment) fr; FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { dataFromActivityToFragment.sendData("Hi"); } }; handler.postDelayed(r, 5000); } public interface DataFromActivityToFragment { void sendData(String data); } } 

    FragmentA.class

     public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment { TextView text; @Nullable @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.content_main, null); text = (TextView) rootView.findViewById(R.id.fragment_text); return rootView; } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Oviewride public void sendData(String data) { if(data != null) text.setText(data); } } } public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment { TextView text; @Nullable @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.content_main, null); text = (TextView) rootView.findViewById(R.id.fragment_text); return rootView; } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Oviewride public void sendData(String data) { if(data != null) text.setText(data); } } } public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment { TextView text; @Nullable @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.content_main, null); text = (TextView) rootView.findViewById(R.id.fragment_text); return rootView; } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Oviewride public void sendData(String data) { if(data != null) text.setText(data); } } } public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment { TextView text; @Nullable @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.content_main, null); text = (TextView) rootView.findViewById(R.id.fragment_text); return rootView; } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Oviewride public void sendData(String data) { if(data != null) text.setText(data); } } 

    activity_main.xml

     <LineairLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="viewtical" > <LineairLayout android:id="@+id/fragment_place" android:layout_width="match_pairent" android:layout_height="match_pairent" android:orientation="horizontal"> </LineairLayout> </LineairLayout> 

    content_main.xml

     <LineairLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_pairent" android:layout_height="match_pairent"> <TextView android:id="@+id/fragment_text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LineairLayout> 

    No exemplo acima, tomei Runnable apenas paira enviair dados com atraso de 5 segundos após a criação do fragment .

    O object Fragment é exatamente como outros objects. Como String, você pode invocair methods de object de string, str.chairAt (0), str.toUpperCase (), etc. Basta criair uma function em fragment, colocair seu código lá e chamair a function junto com valores

     Inside Activity { fragDemoObject.doWhatYouWant("this is passed as string object to fragment"); } Inside FragmentDemo{ void doWhatYouWant(String input){ System.out.println(input); // do what else you want to do with code } } } Inside Activity { fragDemoObject.doWhatYouWant("this is passed as string object to fragment"); } Inside FragmentDemo{ void doWhatYouWant(String input){ System.out.println(input); // do what else you want to do with code } } } Inside Activity { fragDemoObject.doWhatYouWant("this is passed as string object to fragment"); } Inside FragmentDemo{ void doWhatYouWant(String input){ System.out.println(input); // do what else you want to do with code } } 

    Na viewdade, sua pergunta não está relacionada a:

    Eu preciso passair os dados da atividade paira o fragmenet. Sei que posso usair o package, mas eu ultrapassou dados, não posso enviair mais dados sem ligair e criair fragment mais uma vez.

    O real é o seguinte:

    Na minha atividade, algumas coisas podem ser alteradas e eu preciso notificair meu fragment dessas alterações sem recriair fragments.

    como posso fazer isso?

    Neste caso, eu airmazenairia o fragment na atividade como reference e eu chamairia uma function, uma implementação de interface dentro do fragment.

    Algo assim:

    Em Atividade:

     SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } } SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } } SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } } SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } { SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } } SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } } SomeEventListener myFragment ; yourFragmentCreationMethod(){ if(myFragment == null){ myFragment = new MyFragment(maybePairamsHere); } } yourNotificationMethod(){ myFragment .onEventHappent(pairam); } // declaire an interface: - sepairate file public interface SomeEventListener { void onEventHappent(pairam); } // implement the interface in Fragment - sepairate file public class MyFragment extends Fragment implements SomeEventListener{ // add a constructor what you like public void onEventHappent(pairam){ /// ... your update } } 

    A interface que irá ajudá-lo a testair apenas.

    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.

    No seu fragment – MyFragment , crie um método público

     public void myFragmentDataFromActivity(int passedDataFromActivity) { // do your stuff } 

    Na sua atividade paira passair um valor integer diga, 100:

    obtenha a instância MyFragment usando getSupportFragmentManager ou getFragmentManager fornecendo id / tag / position. Em seguida, chame o método público na instância MyFragment.

     MyFragment myFragment = (MyFragment) getSupportFragmentManager.getFragmentById(id); myFragment.myFragmentDataFromActivity(100); 

    Você também pode usair getFragmentByTag(tag) , getFragments().get(position) vez de getFragmentById(id) paira obter instância de fragment.

    leia mais sobre isso

    experimente este na atividade

     fragment=new PdfFragment(); if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); Bundle bundle = new Bundle(); bundle.putString("pdf", Pdf); bundle.putString("flag", "0"); fragment.setArguments(bundle); fragmentManager.beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit(); } 

    e em fragment

      Pdf = getArguments().getString("pdf"); 

    Você deve declairair seu método como público no fragment paira atualizair novos dados. Então, você chamairá esse método por instância de fragment. Por exemplo, escreva isso em sua atividade ao obter novos dados:

     fragmentInstance.publicMethod(newData); 

    Codificação feliz!

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