Change Fragment components through an Activity

1

I'm doing an application with NavigationDrawer , and to not always create another activity , I'm using fragments , where at every click I make replace in FrameLayout that I left set as main. How do I access the components that each fragment has? Ex: TextView (change its text);

My Fragment class

public class EscolheEspecialidadeFragment extends Fragment{

    private TextView tvTeste;
    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_escolhe_especialidade, container, false);
        tvTeste = (TextView)rootView.findViewById(R.id.tvTeste);
        return rootView;
    }

    public void setTextoText(String texto)
    {
        tvTeste.setText(texto);
    }
}

Method responsible for calling fragment

public void clickHojeAmanha(View view)
    {
        EscolheEspecialidadeFragment fragment = new EscolheEspecialidadeFragment();

        FragmentManager fn = getFragmentManager();
        fn.beginTransaction().replace(R.id.content_frame, fragment).commit();

        fragment.setTextoText("teste");
    }

Each time the application attempts to seperate the text, it crashes and closes. Please, where is my error?

    
asked by anonymous 30.08.2016 / 18:36

1 answer

1

Each fragment should be responsible for managing / manipulating the content of its views .

If the need for this change arises outside of it, make available public methods that can be called from abroad.

For example to change the text of a Textview:

public void setTextViewText(String text){

    textView.setText(text);
}
The activity has a reference to Fragment , when you want to change the text of this TextView
fragmentObject.setTextViewText("qualquer coisa");
    
30.08.2016 / 18:47