Initialize element from one fragment into another

Asked

Viewed 97 times

2

I have two fragments attached to my Victoria.

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

In a fragment, to access Activity I use the code

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

this works, but is to start one that is connected to the fragment and not Activity ???

1 answer

0


Use Activity as an intermediary between Fragments(fragment and fragmentB).

  • Declare a method in the fragment, the one whose Textview you want to change:

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

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

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

    Note: The Activity method call should be made through a interface and not by getActivity().nomeMetodo().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.