Initialize element from one fragment in another

2

I have two snippets attached to my activity.

My question is, how do I initialize an element that is in another fragment?

In a fragment, to access the activity I use the code

Textview tv = getActivity().findViewById(R.id.tv);

This works, but to start one that is linked to the fragment and not to activity ???

    
asked by anonymous 18.12.2017 / 18:20

1 answer

0

Use the Activity as an intermediary between fragments (fragmentA and fragmentB).

  • Declare a method in fragmentA, the one whose TextView wants to change:

    public void setText(String text){
    
        textView.setText(text);
    }
    
  • Declare a method in the activity that calls fragmentA:

    public void setFragmentATextView(String text){
        fragmentA.setText(text);
    }
    
  • In fragmentB call the activity method:

    getActivity().setFragmentATextView("qualquer coisa");
    

    Note: The call to Activity methods should be done through a interface and not by getActivity().nomeMetodo() .

18.12.2017 / 18:39