I have a main activity which has a tab layout in which there are two framgents.Following is the code for same.
public void setViewPager(){
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d("hgfdgf","+"+tab.getPosition());
if(tab.getPosition()==0){
fragment=new StudyNotes_fragment();
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter);
//filter_iv_booklet.setVisibility(GONE);
}
else if (tab.getPosition()==1){
fragment2=new Specialbooklet_fragment();
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter2);
//filter_iv_booklet.setVisibility(VISIBLE);
}
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
for (int i=0;i<=studyM.size()-1;i++){
arrayListFilter.add(studyM.get(i).get(i).getCSubjectName());
}
LayoutInflater li = LayoutInflater.from(context);
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(arrayListFilter);
arrayListFilter.clear();
arrayListFilter.addAll(hashSet);
Bundle args = new Bundle();
args.putStringArrayList("array2",arrayListFilter);
args.putSerializable("array4",studyM);
args.putSerializable("tag",makeFragmentName(viewPager.getId(), 1));
fragment.setArguments(args);
return fragment;
case 1:
for (int i=0;i<=specialB.size()-1;i++){
arrayListFilter2.add(specialB.get(i).get(i).getCSubjectName());
}
LayoutInflater li1 = LayoutInflater.from(context);
HashSet<String> hashSet1 = new HashSet<String>();
hashSet1.addAll(arrayListFilter2);
arrayListFilter2.clear();
arrayListFilter2.addAll(hashSet1);
String fragmentTag2 = makeFragmentName(viewPager.getId(), 2);
Bundle args1 = new Bundle();
args1.putSerializable("array", specialB);
args1.putStringArrayList("array2",arrayListFilter2);
args1.putStringArrayList("array3",videosubtitlelist);
args1.putString("tag",fragmentTag2);
fragment2.setArguments(args1);
return fragment2;
//return Specialbooklet_fragment.newInstance(specialB,arrayListFilter2,videosubtitlelist,fragmentTag2);
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
I am using a button which is in toolbar of activity in fragment.I am accessing it in fragment by using getactivity. Below is my code.
rl_filter = activity.findViewById(R.id.rl_filter);
filter_iv = activity.findViewById(R.id.filter_iv);
chipGroup = activity.findViewById(R.id.chipgroup);
applyfilter_tv = activity.findViewById(R.id.applyfilter_tv);
clearfilter_tv = activity.findViewById(R.id.clearfilter_tv);
filter_iv.setOnClickListener(this::onClick);
rl_filter.setOnClickListener(this::onClick);
clearfilter_tv.setOnClickListener(this::onClick);
applyfilter_tv.setOnClickListener(this::onClick);
I am doing same thing in second fragment.My problem is that clicks of only second framgent is working when i am defining the views in both fragments. If i am removing listener and initialisation of buttons from second fragment then first fragment clicks are working. Is there any way i can use the view of activity in both the fragments.
Related
MainActivity containing Navigation drawer. Clicking on navigation drawer item,opening a fragment with viewpager. Clicking on tabs fragment item, another fragment is coming but when pressing back button the viewpager fragment coming blank. How to maintain backstack?
ViewPagerAdapter
public class ViewPagerAdapterProfile extends FragmentStatePagerAdapter{
int mNumOfTabs;
public ViewPagerAdapterProfile(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
if (position ==0) {
return new PersonalDetailsFragment();
} else if (position == 1)
{
return new ProfessionalDetailsFragment();
} else return new EmploymentDetailsFragment();
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public int getItemPosition(#NonNull Object object)
{
return PagerAdapter.POSITION_NONE;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void setListViewHeight(ExpandableListView listView, int group) {
if ((listAdapter.getChildrenCount(i) == 0) && (i == group)) {
Fragment fragment = null;
switch (group) {
case 0:
fragment = new DashboardFragment();
tv_name.clearComposingText();
tv_name.setText("Dashboard");
break;
case 1:
fragment = new MyProfileFrament();
tv_name.clearComposingText();
tv_name.setText("My Profile");
break;
default:
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
int height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
params.height = height;
listView.setLayoutParams(params);
listView.requestLayout();
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
for (Fragment frag : fm.getFragments()) {
if (frag.isVisible()) {
FragmentManager childFm = frag.getChildFragmentManager();
if (childFm.getBackStackEntryCount() > 0) {
childFm.popBackStack();
return;
}
}
}
super.onBackPressed();
}
}
MyProfileFrament
public class MyProfileFrament extends Fragment{
private ViewPager viewPager;
private TabLayout tabLayout;
private String[] pageTitle = {"Personal Details", "Education/Professional Details", "Employement Details"};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_myprofile, container, false);
viewPager = (ViewPager) view.findViewById(R.id.view_pager);
tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
for (int i = 0; i < 3; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPagerAdapterProfile pagerAdapter = new ViewPagerAdapterProfile(requireFragmentManager(), pageTitle.length);
viewPager.setAdapter(pagerAdapter);
//change Tab selection when swipe ViewPager
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//change Tab selection when swipe ViewPager
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//change ViewPager page when tab selected
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
you can maintain the backstack of fragment using :
Fragment fragment=new YourFragmentClass();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();
I am using ViewPager to create 3 Fragment on Activity1,
this is my viewPager adapter :
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment1 tab1 = new Fragment1();
return tab1;
case 1:
Fragment2 tab2 = new Fragment2();
return tab2;
case 2:
Fragment3 tab3 = new Fragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
this is Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("Frag1"));
tab_layout.addTab(tab_layout.newTab().setText("Frag2"));
tab_layout.addTab(tab_layout.newTab().setText("Frag3"));
final ViewPager view_pager = (ViewPager) findViewById(R.id.viewpager);
final ViewPagerAdapter adapter = new ViewPagerAdapter
(getSupportFragmentManager(), tab_layout.getTabCount());
view_pager.setAdapter(adapter);
view_pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_layout));
tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
view_pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
When Activity1 is open it show Fragment1 . But I want to show Fragment2 or Fragment3 instead .
How I can to do that?
Add this line after viewpager.setAdapter(adapter); :
viewPager.setCurrentItem(index);
Index is depending on you , how many fragments you have. tabLayout.getTabCount(); will return you tab count. But index is starting from 0.
If you have 3 Fragment and want to show third Fragment you must use viewPager.setCurrentItem(2);
Set current position of viewpager to your desired possition which is 2 or 3 in your case.
new Handler().post(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(desiredPos);
}
});
seee more
Android ViewPager setCurrentItem not working after onResume
I have 2 tabs and 2 fragments.I did all for this guide
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
but now I see tabs but dont see my fragments.What is the problem?
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch (position) {
case 0:
Direct tab1 = new Direct();
return tab1;
case 1:
AdventuresFragment tab2 = new AdventuresFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Activity with using this adapter:
public class TabsActivity extends Activity {
Fragment directFragmentTab = new Direct();
Fragment adventuresFragmentTab = new AdventuresFragment();
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
() {
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
};
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
In your activity you are using the PagerAdapter class while your fragment handling class is named ViewPagerAdapter. You want to use the ViewPagerAdapter class instead.
Hi I have a TabLayout and ViewPager inside a fragment. But I can not slide beetween tab to come to child fragment (Working normally when in Activity but not work in fragment).
Here is my code for Tablayout inside fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_assign_beacon_to_event, container, false);
//Viewpager and TabLayout
viewPager = (ViewPager)inflateView.findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
tabLayout = (TabLayout)inflateView.findViewById(R.id.tabLayout);
// Inflate the layout for this fragment
return inflateView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
Any here is my Custom Adapter class
private class CustomAdapter extends FragmentPagerAdapter {
private String fragments[] = {"Assign Event", "Manage Event"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// return new AssignEventToBeacon();
return new Test1();
case 1:
return new ManageEventAssigned();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
I doubt i have problem with this line:
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
Anyhelp is much appreciate, thanks
I have done a similar project and here is my code for the fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.outer_fragment, container, false);
setHasOptionsMenu(true);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
Log.v("Layout","Tabs");
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setTabTextColors(Color.parseColor("#707070"), Color.parseColor("#FFFFFF"));
assert viewPager != null;
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "PHOTOS");
adapter.addFragment(new Tab2Fragment(), "HI-FIVES");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
You need to use getChildFragmentManager() in Fragment instead of getFragmentManager().
From getChildFragmentManager() documentation
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
From getFragmentManager() documentation
Return the FragmentManager for interacting with fragments associated
with this fragment's activity.
In simple words,
Use getChildFragmentManager() for Child Fragments
Use getFragmentManager() for Fragments inside Activity
One can see #this answer for complete code.
i use this tutorial for creating tab.
and now i have a recyclerview in each fragment and i want to notify them from mainactivity. how to access the adapter in fragment?
i use this for calling refreshData() method in fragment:
TabFragment1 tabFragment = (TabFragment1) getSupportFragmentManager().findFragmentByTag(TabFragment1.class.getSimpleName());
if (tabFragment != null) {
tabFragment.refreshData();
}
but that return null.
mainActivity:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
case 3:
TabFragment4 tab4 = new TabFragment4();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
One of myTabFragment:
public CardAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView v = (RecyclerView) inflater.inflate(R.layout.tab_fragment_1, container, false);
SetupRecycleView(v);
return v;
}
public void refreshData() {
adapter.notifyDataSetChanged();
}
void SetupRecycleView(RecyclerView recList) {
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(G.context);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//recList.setLayoutManager(new GridLayoutManager(G.context, 2));
recList.setLayoutManager(llm);
List<StructGhaza> ghazas = StructGhaza.getAllGhaza("2");
adapter = new CardAdapter(ghazas);
recList.setAdapter(adapter);
}
The CardAdapter:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.GhazaViewHolder> {
private List<StructGhaza> ghazas;
public CardAdapter(List<StructGhaza> ghazaList) {
this.ghazas = ghazaList;
}
#Override
public int getItemCount() {
return ghazas.size();
}
#Override
public void onBindViewHolder(GhazaViewHolder ghazaViewHolder, int position) {
StructGhaza ghaza = ghazas.get(position);
ghazaViewHolder.vTitle.setText(ghaza.Name);
//----Load Image
Glide.with(G.context)
.load(ghaza.Aks)
.placeholder(R.drawable.loading_spinner)
.crossFade()
.into(ghazaViewHolder.itemImg);
//---------------
ghazaViewHolder.Rate.setRating(ghaza.Star);
ghazaViewHolder.sampleLayout.setHoverView(ghazaViewHolder.hover);
ghazaViewHolder.sampleLayout.addChildAppearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipInX);
ghazaViewHolder.sampleLayout.addChildDisappearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipOutX);
}
#Override
public GhazaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.fragment_carditem, viewGroup, false);
return new GhazaViewHolder(itemView);
}
public static class GhazaViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected BlurLayout sampleLayout;
protected View hover;
protected ImageView itemImg;
protected RatingBar Rate;
public GhazaViewHolder(View v) {
super(v);
sampleLayout = (BlurLayout) v.findViewById(R.id.sample);
itemImg = (ImageView) v.findViewById(R.id.item_img);
hover = LayoutInflater.from(G.context).inflate(R.layout.fragment_hover, null);
vTitle = (TextView) v.findViewById(R.id.titleTv);
Rate = (RatingBar) v.findViewById(R.id.rating);
}
}
}
EDIT:
After many test, the previous answer work with Android < 21, but for Android > 21 it's little bit weird, it doesn't seems to work in the same way.
Finally, I solved it like that, and it works everywhere:
In your adapter:
HashMap<Integer, Fragment> mPageReferenceMap = new HashMap<>();
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mPageReferenceMap.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(position);
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
And you call getFragment where you want in your activity like that:
int index = viewPager.getCurrentItem();
ViewPagerAdapter adapter = ((ViewPagerAdapter)viewPager.getAdapter());
final YourFragment tabFragment = (YourFragment) adapter.getFragment(index);
PREVIOUS ANSWER :
Warning : it doesn't really work with Android > 21
I had the same problem. Finally, i did'nt use id or tag.
Instead of using:
CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_custo_tag));
use this:
CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().getFragments().get(0);
to get instance of CustomFragment.
I have put get(0) as your position of CustomFragment instance is at zero.
I found this issue here:
Set and get using tag a fragment in android
This is late but I hope this will be helpful for someone. To find fragment by tag we can do this:
String tag=getSupportFragmentManager().getFragments().get(index).getTag();
SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(tag);