For FragmentManager findFragmentById, return nul, findfragmentbyid
First, let's look at the two generation methods of Fragment.
1. Generate with xml tags
Add an xml tag to the fragment's host activity.
1 <fragment2 android:id="@+id/fragment_newsContent"3 android:name="com.firstcode.section4_news.NewsContentFragment"4 android:layout_width="match_parent"5 android:layout_height="match_parent"/>
The fragment class created by name for you
This method has already generated fragment when the activity is created.
Operations for obtaining fragment instances in an Activity:
1 NewsContentFragment fragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.fragment_newsContent);
Ii. Dynamic generation using java code
Add FrameLayout to the view file of the fragment host activity for placeholder
1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"2 android:id="@+id/fragmentContainer"/>
Fragment generation in Activity
1 FragmentManager fm = getFragmentManager (); 2 fm. beginTransaction () 3. add (R. id.FragmentContainer, "The fragment class instance you created ")
. Commit ();
Problem Analysis:
I am using FragmentManager. findFragmentById to return nul. This is where I generate fragment in the second way, that is, the real parameter in findFragmentById
I entered the FrameLayout Id, instead of the fragment Id. Therefore, null is returned.
Solution:
1. If fragment is generated statically, use getFragmentManager (). findFragmentById to obtain the fragment instance.
2. If you use java code to dynamically generate fragment, you just need to get a new fragment instance and use getFragmentManager (). findFragmentById.
3. Pay attention to the labels FrameLayout and fragment in the xml file.
There is another problem. I also solved this problem by adding text to textview In the fragment view.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
The reason is that the Id parameter in the fragment add generated by the java code fills in the fragment id, so the fragment view is not generated.
The best documentation for understanding the two fragment generation methods is google's official Android Training. Below is a Chinese translation.
Add fragment using xml tags
Dynamically add fragment using java code