How to better modularize the ViewPager order/tab names - android

I have a ViewPager that works well, but I want to make it a little better.
Right now in my PagerAdapter class, in the getItem method I use a switch statement:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragmentChicken tabChicken = new TabFragmentChicken();
return tabChicken;
case 1:
TabFragmentFish tabFish = new TabFragmentFish();
return tabFish;
...
And then over in my activity class, I set the tabs name like so:
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Chicken"));
tabLayout.addTab(tabLayout.newTab().setText("Fish"));
...
Is there a way I can better modularize this? For instance if I wanted to change the order of the tabs I'd have to change both the switch statement and the tab names. Is there another class or structure I can use to keep it all in one place so I only need to update one thing and not have to bother with the switch/adding tab text changes?

You can create a custom Object that will hold the title and the fragment, then use a list of this Object within your adapter. Here is a small way of implementing it:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.chahinemouhamad.parrrot.home.recent.RecentFragment;
public class HomePagerAdapter extends FragmentPagerAdapter {
private final PagerFragment[] pagerFragments;
public HomePagerAdapter(final FragmentManager fm) {
super(fm);
pagerFragments = new PagerFragment[] {
new PagerFragment("item 1", RecentFragment.newInstance()),
new PagerFragment("item 2", RecentFragment.newInstance())
};
}
#Override public Fragment getItem(final int position) {
return pagerFragments[position].fragment;
}
#Override public int getCount() {
return pagerFragments.length;
}
#Override public CharSequence getPageTitle(final int position) {
return pagerFragments[position].title;
}
class PagerFragment {
public final String title;
public final Fragment fragment;
public PagerFragment(String title, Fragment fragment) {
this.title = title;
this.fragment = fragment;
}
}
}

Related

FragmentPagerAdapter strange behavior

So i have the next problem with FragmentPagerAdapter. I have a TabLayout with 3 tabs representing 3 fragments that i can switch. So when i switch to third fragment, for some reason the first one disappears (or its view). Does anyone know how to fix this problem? Thanks in advance.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private static final int FRAGMENT_COUNT = 3;
private final List<Fragment> listOfFragments = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return listOfFragments.get(position);
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
public void addFragment(Fragment fragment) {
listOfFragments.add(fragment);
}
}
This is the code for FragmentPagerAdapter.
And i think i fixed this :) Only thing i did is to override the FragmentPagerAdapter destroyItem() method, with empty body (no super).
I don't know what is your problem. but if in your app only 3 fragments are there than you can try setOffscreenPageLimit method of ViewPager
ViewPager.setOffscreenPageLimit(3);
One of the problems here is a slightly confusing API.
In FragmentPagerAdapter, getItem(int position) actually means "create item". In other words, you shouldn't try to manually cache the Fragments inside a list in your Adapter.
#Override
public Fragment getItem(int position) {
return listOfFragments.get(position); //No! don't do this
}
Even though it may see counter-intuitive, you should actually create a new instance of the Fragment you want inside getItem, sticking very closely to the official Google example:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.getInstance();
case 1:
return SecondFragment.getInstance();
}
}
Otherwise you will run into problems where the FragmentManager's cache and your own List<Fragment> cache are out-of-sync. In short, caching of Fragments is handled by the FragmentManager and you don't need to roll-your-own caching.
I don't know really what happen but this is my code, hope this help you
public class AdapterFragmentViewPager extends FragmentPagerAdapter {
private List<Fragment> fragmentList = new ArrayList<>();
public AdapterFragmentViewPager(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
and this is my Tablayout:
private AdapterFragmentViewPager adapterFragmentViewPager = new AdapterFragmentViewPager(getSupportFragmentManager());
TabLayout.Tab home = tabLayout.newTab();
tabLayout.addTab(home);
TabLayout.Tab newest = tabLayout.newTab();
tabLayout.addTab(newest);
TabLayout.Tab author = tabLayout.newTab();
tabLayout.addTab(author);
TabLayout.Tab category = tabLayout.newTab();
tabLayout.addTab(category);
TabLayout.Tab saved = tabLayout.newTab();
tabLayout.addTab(saved);
adapterFragmentViewPager.addFragment(FragmentHome.newInstance());
adapterFragmentViewPager.addFragment(FragmentQuote.newInstance());
adapterFragmentViewPager.addFragment(FragmentAuthor.newInstance());
adapterFragmentViewPager.addFragment(FragmentCategory.newInstance());
adapterFragmentViewPager.addFragment(FragmentFavorites.newInstance());
viewPager.setAdapter(adapterFragmentViewPager);
tabLayout.setupWithViewPager(viewPager);

Both Fragment in ActionBar return true for fragment.isVisible()

In my MainActivity with ActionBar I listen to a listener from a DialogFragment and based on which Fragment of ActionBar i am on, I need to do some things.
I am using below code to get the current fragment and check which of the two ActionBar fragment i am on:
private Fragment getVisibleFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
but fragment.isVisible() returns true for both the fragments. Why would that be? Is there another flag I need to consider?
Below is my FragmentPagerAdapter implentation:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new ReceivedListFragment();
case 1:
return new SentListFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return context.getString(R.string.title_section1).toUpperCase(l);
case 1:
return context.getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
It seems you are using a ViewPager and you need to find out which is the currently selected view. The problem in your approach, in my opinion, is that the viewpager keeps instance of at least two fragments. It seems you have two fragments only, both of the fragments are kept by the viewpager and which is why you get the isVisible true for both the fragments.
If your only need is to get the currently selected fragment on the viewpager, please try this method from the viewpager class:
mViewPagerInstance.getCurrentItem();
which will give you the currently selected fragment index.
Another way would be to add a PageChangeListener for your viewpager and then listen to page change events:
class MyActivity extends Activity{
private int curPage;
private static class MFragChangeListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
curPage = position;
}
}
........... /* Rest of your code */
mViewPagerInstance.setOnPageChangeListener(new MFragChangeListener());
/* Now access curPage to get the current selected page index whenever you need it. */
Please refer to this SO post as well.

android viewpager with fragments using FragmentPageAdapter dynamic add, remove

I have an application with tabhost and viewpager.
I have one tab, fragment as fixed.
I have to add tab,fragments dynamically on click radio button in radiogroup from the first fragment.
MyPagerAdapter class:
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
public class MyViewPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments = new ArrayList<Fragment>();
FragmentManager fm;
public List<Fragment> getFragments() {
return fragments;
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
public MyViewPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fm = fm;
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(Fragment fragment) {
this.fragments.add(fragment);
notifyDataSetChanged();
}
public void removeFragments() {
try {
List<Fragment> newList = new ArrayList<Fragment>();
Fragment general = fragments.get(0);
newList.add(general);
this.fragments.clear();
this.fragments = new ArrayList<Fragment>();
this.fragments = newList;
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeItemFromFrament(ViewGroup container, int position, Object object) {
try {
try {
container.removeViewAt(position);
((ViewPager) container).setCurrentItem(position - 1);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyPagerFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyViewPageFragment extends Fragment {
private static View mView;
public static final MyViewPageFragment newInstance(int layoutId) {
MyViewPageFragment f = new MyViewPageFragment();
Bundle b = new Bundle();
b.putInt("layout", layoutId);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("layout");
try {
mView = inflater.inflate(layout, container, false);
} catch (Exception e) {
}
return mView;
}
}
Im trying to add fragments to adapter like this:
Fragment fragment = MyViewPageFragment.newInstance(R.layout.tab_content_layout);
((MyViewPageAdapter) mViewPager.getAdapter()).addFragment(fragment);
My Problem:
On first time, the pages are added properly, after remove all views(except first fragment) and trying to add another set of tabs, fragments the views are not visible and the getSupportFragmentmanager.getFragments().size() is incorrect.
I tried to remove the views from viewpager with fragment manager
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
After adding tabs, fragments on pagescrolled the getSupportFragmentManager().getFragments.get(arg0) returns null.
Note:
I have to maintain the state of the first fragment, so FragmentStatePagerAdapter and getItemPosition return POSITION_NONE is not acceptable.
In the same way that you don't specifically call removeView() on a ListView from a ListAdapter to get rid of an item, you don't directly remove a Fragment with FragmentManager from a FragmentPagerAdapter.
You have to override getItemPosition(), but you have to provide a little more intelligent implementation than just returning POSITION_NONE all the time.
If your first fragment never changes, then always return POSITION_UNCHANGED when that fragment is passed to getItemPosition()
Think about it as a conversation between you and the ViewPager/FragmentPagerAdapter. Here's an example:
You: "I need to change the fragments around." (call notifyDataSetChanged)
Adapter: "Heads up, I'm going to change everything around now." (callback startUpdate)
Adapter: "How many tabs do you want?" (callback getCount())
You: Three. (return '3')
Adapter: "Okay, what do you want me to do with this first one?" (callback getItemPosition)
You: "I want to keep that one right where it is." (return POSITION_UNCHANGED)
Adapter: "Great, what about this second one?" (callback getItemPosition)
You: "I want to move it to the third tab." (return '2')
Adapter: "All right, what about the third one?" (callback getItemPosition)
You: "I want to get rid of that one completely." (return POSITION_NONE)
Adapter: "Okay, I have a space for the second tab, what fragment do you want me to use?" (callback getItem)
You: "This one." (return fragment for position == 1)
Adapter: "I'm done changing everything, kthxbye." (callback finishUpdate)
I might not have the order of calls exactly right, but the basic idea is there.
If you need to maintain the state of the fragments that are kicked out, you could override getItem() and destroyItem() to help you with that:
private FragmentManager mFragmentManager;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
#Override
public Fragment getItem(int position) {
// figure out which fragment you want at this position
Fragment fragment = new MyFragment();
// retrieve your savedState from wherever you put it
fragment.setInitialSavedState(savedState);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
Fragment.SavedState savedState = mFragmentManager.saveFragmentInstanceState(fragment)
// save your fragment state somewhere here
super.destroyItem(container, position, object);
}
Your fragments will need to implement saveState() and restoreState() for this to work.
I tried similar requirement as yours with a FragmentStatePagerAdapter which worked fine. May be it could help you.
To add the new fragment:
SIZE = SIZE +1;
adapter.instantiateItem(viewPager, SIZE-1);
adapter.notifyDataSetChanged();
In getItem(), for the "position" create and return the new fragment (I used a switch statement here)
Update the getCount() method to return the new SIZE.
Let me know if you would like me to share the code.

Why am I getting getString error? And how to resolve?

I am testing out the FragmentPagerAdapter and I had it all in a single class before. And everything worked, but once I separated SectionsPagerAdapter class, the getString doesn't work under the getPageTitle function.
I know getPageTitle is part of the PagerAdapter class, but I want to know what the best way to have that function included in this class. Do I need to extend the class?
SectionsPageAdapter class
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
// A FragmentPagerAdapter that returns a fragment corresponding to one of the sections/tabs/pages.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.myFriendsTab).toUpperCase(l);
case 1:
return getString(R.string.myDealsTab).toUpperCase(l);
case 2:
return getString(R.string.featuredDealsTab).toUpperCase(l);
case 3:
return getString(R.string.browseCategoriesTab).toUpperCase(l);
case 4:
return getString(R.string.localDealsTab).toUpperCase(l);
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
MainActivity class
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
// Fragment PagerAdapter keeps every loaded fragment in memory.
// If too memory intensive, switch to FragmentStatePagerAdapter.
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager; // ViewPager that will host section contents.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creates the adapter that will return a fragment for each of the primary sections.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), null);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
getString(int) only works for Classes that have access to a Context - Fragments, Activities, etc.
Given that this an Adapter class, it won't have direct access to a Context, so you should probably pass one in with the constructor.
private Context mContext = null;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
and then use the member field to access getString(int)
return mContext.getString(R.string.myFriendsTab).toUpperCase(1);
as panini said, getString method need to be called on Context, follow these steps :
Step 1 : in the adapter class, create a field to store the Context on it.
private Context mContext
Step 2 : in the adapter class, adjust the constructor to pass the Context as the first parameter.
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
Step 3 : in the adapter class, and inside the getPageTitle method, call the getString on the Context field mContext,
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return mContext.getString(R.string.myFriendsTab).toUpperCase(l);
case 1:
return mContext.getString(R.string.myDealsTab).toUpperCase(l);
case 2:
return mContext.getString(R.string.featuredDealsTab).toUpperCase(l);
case 3:
return mContext.getString(R.string.browseCategoriesTab).toUpperCase(l);
case 4:
return mContext.getString(R.string.localDealsTab).toUpperCase(l);
}
return null;
}
Step 4 : wherever you used the adapter adjust it to include the Context parameter as we defined in the constructor.
in MainActivity class, adjust the constructor to be like this :
mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());

Is it possible to access the current Fragment being viewed by a ViewPager?

I have an app with a ViewPager and three Fragments. I'm trying to figure out how to get the current Fragment being viewed so I can get at its arguments.
I have an OnPageChangeListener grabbing the current page index, but
ViewPager.getChildAt(int position);
returns a View. What's the relationship between this View and the current Fragment?
I finally found an answer that worked for me. Basically, you can access the fragment for a viewPager page by using the tag "android:switcher:"+R.id.viewpager+":0".
I've solved this problem the other way round.
Instead of searching for the fragment from the activity, I'm registering the Fragment during it's onAttach() method at it's owner activity and de-registering it in the onStop() method.
Basic Idea:
Fragment:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
mActivity = (IMyActivity)activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString() +" must be a IMyActivity");
}
mActivity.addFragment(this);
}
#Override
public void onStop() {
mActivity.removeFragment(this);
super.onStop();
}
IMyActivity:
public interface IFriendActivity {
public void addFragment(Fragment f);
public void removeFragment(Fragment f);
}
MyActivity:
public class MyActivity implements IMyActivity{
[...]
#Override
public void addFragment(Fragment f) {
mFragments.add(f);
}
#Override
public void removeFragment(Fragment f) {
mFragments.remove(f);
}
}
Edit - Don't do this. If you're tempted to, read the comments for why it's a bad idea.
On the odd-chance you're still trying to solve this problem:
Extend FragmentPagerAdapter. In the constructor, build the Fragments you need and store them in a List (array/ArrayList) of Fragments.
private final int numItems = 3;
Fragment[] frags;
public SwipeAdapter (FragmentManager fm) {
super(fm);
//Instantiate the Fragments
frags = new Fragment[numItems];
Bundle args = new Bundle();
args.putString("arg1", "foo");
frags[0] = new MyFragment();
frags[1] = new YourFragment();
frags[2] = new OurFragment();
frags[2].setArguments(args);
}
Then for getItem(int position), you can do something like
public Fragment getItem(int position) {
return frags[position];
}
I'm not sure if this is the generally accepted way of doing it but it worked for me.
Edit
This is really not a good way to go. If you plan on handling orientation changes or your app going into the background, then this will probably break your code. Please read the comments below this answer for more info. Rather use #James 's answer
Yes, it's possible if you are using FragmentStatePagerAdapter.
ViewPager vp;
//...
YourFragment fragment = (YourFragment) adapter.instantiateItem(vp, vp.getCurrentItem());
PLEASE DON'T USE THIS
Make your adapter extend the following FragmentStatePagerWithCurrentAdapter class and instead of implementing getItem implement the same code into getItemAtIndex
Set the ViewPager OnPageChangeListener, to the instance of the adapter.
When you need to access the current Fragment you just call adapter.getCurrentItem().
package your.package;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.ViewGroup;
public abstract class FragmentStatePagerWithCurrentAdapter
extends FragmentStatePagerAdapter
implements OnPageChangeListener {
int currentPage = 0;
private SparseArray<Fragment> mPageReferenceMap = new SparseArray<Fragment>();
public FragmentStatePagerWithCurrentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public final Fragment getItem(int index) {
Fragment myFragment = getItemAtIndex(index);
mPageReferenceMap.put(index, myFragment);
return myFragment;
}
public abstract Fragment getItemAtIndex(int index);
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(Integer.valueOf(position));
}
public Fragment getCurrentItem() {
return mPageReferenceMap.get(currentPage);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int newPageIndex) {
currentPage = newPageIndex;
}
}
I used as reference the following blog post: http://tamsler.blogspot.com/2011/11/android-viewpager-and-fragments-part-ii.html
It's been explained here : http://developer.android.com/guide/topics/fundamentals/fragments.html
In OnCreateView you must return a view to draw a UI for your fragment, I think that's the relationship.
Also this question might be similar: Get focused View from ViewPager
You can do so:
- On the class extent of a view pager adapter (such as PagerAdapter , FragmentStatePagerAdapter...) override method instantiateItem :
#Override
public Object instantiateItem(ViewGroup container, int position) {
final Fragment frag = (Fragment) super.instantiateItem(container, position);
if(frag instanceof ListNoteOfTypeFragment){
final ListNoteOfTypeFragment listNoteOfTypeFragment = (ListNoteOfTypeFragment) frag;
//do whatever you want with your fragment here
listNoteOfTypeFragment.setNoteChangeListener(mListener);
}
return frag;
}
Definitive answer that works seamlessly (but small hack):
somewhere in page fragment's layout:
<FrameLayout android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone" android:id="#+id/fragment_reference">
<View android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone"/>
</FrameLayout>
in fragment's onCreateView():
...
View root = inflater.inflate(R.layout.fragment_page, container, false);
ViewGroup ref = (ViewGroup)root.findViewById(R.id.fragment_reference);
ref.setTag(this);
ref.getChildAt(0).setTag("fragment:" + pageIndex);
return root;
and method to return Fragment from ViewPager, if exists:
public Fragment getFragment(int pageIndex) {
View w = mViewPager.findViewWithTag("fragment:" + pageIndex);
if (w == null) return null;
View r = (View) w.getParent();
return (Fragment) r.getTag();
}
Jorge Garcia's FragmentStatePagerWithCurrentAdapter is a very good solution but it needs a minor improvement. In case the activity gets destroyed and re-created in response to a configuration change or something like that the getItem will not be called for the fragments that were saved and retrieved by the fragment manager. So I override getItem normally in my subclass and I put the following in the FragmentStatePagerWithCurrentAdapter
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object item = super.instantiateItem(container, position);
if ( item instanceof Fragment ) {
pageReferenceMap.put(position, (Fragment)item);
}
return item;
}
The instantiateItem is called every time the fragment in that position is accessed.
Or just save all Fragments in a map:
public class MyFragment extends Fragment implements OnPageChangeListener {
private ViewPager viewPager;
private FragmentStatePagerAdapter viewAdapter;
private View rootView;
private Map<Integer, Fragment> fragments = new HashMap<Integer, Fragment>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.introdution, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
viewAdapter = new ViewAdapter(getFragmentManager());
viewPager.setAdapter(viewAdapter);
viewPager.addOnPageChangeListener(this);
return rootView;
}
private class ViewAdapter extends FragmentStatePagerAdapter {
public ViewAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
Fragment result = null;
switch (position) {
case 0: result = Fragment1.newInstance(); break;
case 1: result = Fragment2.newInstance(); break;
}
if (result != null)
fragments.put(position, result);
return result;
}
#Override
public int getCount() {
return 2;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
Fragment currentFragment = fragments.get(position);
}
}
I think there is the better way by using this
Log.i(TAG, "getCurrentItem " + mViewPager.getCurrentItem());
Can get the current display fragment page.

Categories

Resources