I want to set some TextViews in fragments inside of a ViewPager. i'm setting my TextViews in onActivityCreated function of my fragments when it's instantiate pages . according to some posts returning POSITION_NONE in getItemPosition solve my problem but because of deleting all views everytime it's not an efficient way.so i've change it to instatiateItem(ViewGroup container, int position) but when i returning the view of my Fragments it throws :
ClassCastException : android.Widget.LinearLayout cannot be cast to android.support.v4.app.Fragment
here is my instantiateItem(ViewGroup container, int position) function, does anybody know how can i manage this exception? or how can i refresh a TextView in a Fragment inside of a ViewPager? Thanks in Advance
@Override
public Object instantiateItem(ViewGroup container, int position)
{
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position == 3) {
view = inflater.inflate(R.layout.projecttracking_detail_customerproject_fragment, null);
((ViewPager) container).addView(view, 0);
}
else if(position == 2) {
view = inflater.inflate(R.layout.projecttracking_detail_projectinformation_fragment, null);
((ViewPager) container).addView(view, 0);
}
return view;
}
If you have a fragment based ViewPager
then you can't override instantiateItem()
to return a View
as that returned object will be treated like a Fragment
later(what the exception is telling you).
I don't fully understand what you want so, if you want to update some of the views(from all of the fragments?) from the fragments then you could use the POSITION_NONE
option.
You could also just update the current stored fragments from the ViewPager
and let the other query for data(in the onCreateView()
) when they get recreated as the user swipes towards them. For a FragmentPagerAdapter
you could use this to access the current stored visible fragments:
PageFragment pf = (PageFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.theIdOfTheViewPager + ":" + viewPager.getCurrentItem());
pf.updateViews();
you could get the other two stored fragments(one in each side of the visible fragment) by modifying the value returned by viewPager.getCurrentItem()
with -/+1;. Your fragments will need to be modified so in the onCreateView()
you test if there is new data and use that.
If you use a FragmentStatePagerAdapter
there are also ways of getting the current stored fragments.