Tags
Fragment not specified automatically. You must assign them yourself. There are several places for this, depending on how you attach the fragment: in XML or dynamically.
If it is specified in XML, you can install it as follows:
<fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:tag="your_tag" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" />
If you add a fragment dynamically, you can do it as follows:
ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment, "your_tag"); fragmentTransaction.commit();
In both examples, find "your_tag" .
Then, when you call getTag() on you Fragment , you will get the result "your_tag" .
When using your FragmentPagerAdapter fragments, tags are automatically assigned based on getItemId(int) , which by default returns the position of the pager. Therefore, the call to getTag() will return the position of the fragment in the ViewPager .
If you use FragmentStatePagerAdapter tags, NOT . If in this case you need to switch to the first type of adapter or use a different method to link to your fragments.
From the adapter implementation, I know that you have only 3 pages, so the FragmentPagerAdapter more suitable for you.
As evidence, this is part of the description from the FragmentStatePagerAdapter :
This version of the pager is more useful when there are a large number of pages that look more like a list view.
and the following description from the FragmentPagerAdapter :
This version of the pager is best used when there are several usually more static fragments that should be unloaded, for example, a set of Tabs.
If you insist on using the FragmentStatePagerAdapter, read on:
I guess you need tags in order to find your snippets later. Instead, the tags retain the link to the snippet. Your activity method ((MainActivity)getActivity()).setHistoryFragment(myTag); already expecting a fragment of a certain type. So you can call it this way: ((MainActivity)getActivity()).setHistoryFragment(this); Later, instead of searching for a fragment, check to see if it is null and use it.