What is the difference between this assignment of a reference to a fragment

Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1); frag1.getView().findViewById(R.id.textView_1)).setText(""); 

from ( Fragment_1 - class realizing fragment)

  Fragment_1 frag1 = new Fragment_1(); frag1.getView().findViewById(R.id.textView_1)).setText(""); 

As far as I understand, the link is assigned to the same layout file, but only the first option works! Why?

  • Perhaps due to the fact that a new instance of the Fragment_1 object is being created - redL1ne

1 answer 1

  1. In the first case, you get a link to the fragment registered in the activation, for which the life cycle methods have already been called, incl. load and display markup. At the same time, if you actually did not add the fragment (or have already deleted it), you will get null

  2. In the second, you create an instance of a fragment class for which only its constructor is called. In activit it is not added, we are locking its life cycle methods were not caused by the system and its markup is not loaded.

Conclusion : access to the markup of the fragment can be obtained only by adding it to the activation and getting it from the activation.