Change Fragment components through an Activity

Asked

Viewed 885 times

2

I’m making an application with NavigationDrawer, and not to create another activity, I’m using fragments, where every click replace in the FrameLayout that I left set as main. How I access the components that each fragment does it? Ex: TextView (alter his text);


My class Fragment

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");
    }

Every time the application tries to set the text, it crashes and closes. Please, where is my error?

  • You want that code on Activity change the text of a Textview existing in the layout of Fragment?

  • Yes, it would be possible?

1 answer

1


Each Fragment shall be responsible for managing/handling the content of its views.

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

For example to change the text of a Textview:

public void setTextViewText(String text){

    textView.setText(text);
}

To Activity has a reference to Fragment, when you want to change the text of this Textview uses the method like this:

fragmentObject.setTextViewText("qualquer coisa");
  • textview findviewbyid, I do in the Fragment class, onCreateView or my main activity?

  • Like the Textview is in the layout of Fragment, the findViewById() has to be done in the Fragment

  • Friend, please. Look at my other answer with my class

  • The problem is that the transaction is not applied immediately after the commit, so, when the method setTextViewText() is called, the onCreateView() has not yet been executed. Between the line where the commit and the call to the method includes this: fn.executePendingTransactions();

  • 1

    Exactly, it worked! Thank you

Browser other questions tagged

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