android fragment设置tag,Android FragmentStatePagerAdapter, how to tag a fragment to find it later

问题

When using the FragmentStatePageAdapter I get the fragments like this:

@Override

public Fragment getItem(int position) {

return new SuperCoolFragment();

}

However, later on my code I need to find this fragment to set a property. In some other parts of the app where I use fragments I basically tag them and look for them using findFragmentByTag(TAG) but with now I don't know how to do it.

How do can I find the fragments using the FragmentStatePageAdapter?

回答1:

* EDIT *

As @ElliotM pointed out, there is a better solution. No need to change anything in your adapter, just get the fragment with:

Fragment myFragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());

* OLD SOLUTION *

Best option is the second solution here:

http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

In short: you keep track of all the "active" fragment pages. In this case, you keep track of the fragment pages in the FragmentStatePagerAdapter, which is used by the ViewPager..

public Fragment getItem(int index) {

Fragment myFragment = MyFragment.newInstance();

mPageReferenceMap.put(index, myFragment);

return myFragment;

}

To avoid keeping a reference to "inactive" fragment pages, we need to implement the FragmentStatePagerAdapter's destroyItem(...) method:

public void destroyItem(View container, int position, Object object) {

super.destroyItem(container, position, object);

mPageReferenceMap.remove(position);

}

... and when you need to access the currently visible page, you then call:

int index = mViewPager.getCurrentItem();

MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter());

MyFragment fragment = adapter.getFragment(index);

... where the MyAdapter's getFragment(int) method looks like this:

public MyFragment getFragment(int key) {

return mPageReferenceMap.get(key);

}

--- EDIT:

Also add this in your adapter, for after an orientation change:

/**

* After an orientation change, the fragments are saved in the adapter, and

* I don't want to double save them: I will retrieve them and put them in my

* list again here.

*/

@Override

public Object instantiateItem(ViewGroup container, int position) {

MyFragment fragment = (MyFragment) super.instantiateItem(container,

position);

mPageReferenceMap.put(position, fragment);

return fragment;

}

回答2:

I've found another way of doing it, not sure if there would be any issues for using it, it seems ok to me.

I was checking at the code for FragmentStatePageAdapter and I saw this method:

@Override

52 public Object More ...instantiateItem(View container, int position) {

53 // If we already have this item instantiated, there is nothing

54 // to do. This can happen when we are restoring the entire pager

55 // from its saved state, where the fragment manager has already

56 // taken care of restoring the fragments we previously had instantiated.

57 if (mFragments.size() > position) {

58 Fragment f = mFragments.get(position);

59 if (f != null) {

60 return f;

61 }

62 }

63

64 if (mCurTransaction == null) {

65 mCurTransaction = mFragmentManager.beginTransaction();

66 }

67

68 Fragment fragment = getItem(position);

69 if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);

70 if (mSavedState.size() > position) {

71 Fragment.SavedState fss = mSavedState.get(position);

72 if (fss != null) {

73 fragment.setInitialSavedState(fss);

74 }

75 }

76 while (mFragments.size() <= position) {

77 mFragments.add(null);

78 }

79 fragment.setMenuVisibility(false);

80 mFragments.set(position, fragment);

81 mCurTransaction.add(container.getId(), fragment);

82

83 return fragment;

84 }

You can use this method to get the fragment already instated for that particular position. So if you want to get Fragment at position 1, you just need to call:

myFragmentStatePageAdpater.instantiateItem(null, 1)

Hope that helps

回答3:

I implemented this by adding a getItemTag(int position) function to FragmentStatePagerAdapter. A drop-in version of the updated file is here if anyone else wants to go this route.

回答4:

Solution with storing fragments to a HashMap in your getItem() method does not work if your activity is re-created!

Problem is, default implementation of the FragmentStatePagerAdapter restores fragments directly from the FragmentManager without calling the getItem() method. This means that you'll never get a chance to store a reference to your fragment.

For more info, see source code:

FragmentStatePagerAdapter#restoreState.

This basically means that the only way to get a reference to your fragment is by resorting to reflections. This is relatively* safe** in case youre using support library.

Here's how:

@SuppressWarnings("unchecked")

public Fragment getFragment(int position) {

try {

Field f = FragmentStatePagerAdapter.class.getDeclaredField("mFragments");

f.setAccessible(true);

ArrayList fragments = (ArrayList) f.get(this);

if (fragments.size() > position) {

return fragments.get(position);

}

return null;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

relatively* means that its not as dangerous as using reflection on framework classes. Support classes are compiled into your app and there is no way that this code will work on your device but will crash on some other device. You can still potentially break this solution by updating support library to a newer version

safe** its never really safe to use reflections; however you have to resort to this method when a library you're using has design flaws.

回答5:

As @Lancelot mentioned, You may just call and cast result to your SuperCoolFragment:

SuperCoolFragment frag = (SuperCoolFragment) yourFragmentStatePageAdpater.instantiateItem(null, position);

回答6:

I tried Frank's answer that suggests Second Approach from the tutorial linked in it, bot for some reason after adding method getFragment() to my ViewPagerAdapter I can't access it via mViewPager.getAdapter.getFragment() as if it doesn't exist, so I moved mPageReferenceMap declaration from the ViewPagerAdapter to the enclosing class so it is easily accessed from any point of the enclosing class (in my case it is MainActivity's callback method from other fragment) which finally makes it possible to pass data between fragments.

Thanks to Frank and feel free to implement my fixture if you like me face issue with accessing custom getFragment method.

回答7:

Another solution is to copy paste the source code of FragmentStatePagerAdapter and add a getFragment method:

public Fragment getFragment(int position) {

if (position >= mFragments.size()) {

return null;

}

return mFragments.get(position);

}

回答8:

Override setPrimaryItem, and using that position, it would be the right page index:

@Override

public void setPrimaryItem(ViewGroup container, int position, Object object) {

super.setPrimaryItem(container,position,object);

if (position == 1) {

currentPageIndex=cameraFragment.pageIndex;

}

回答9:

Create a holder to hold the new SuperCoolFragment object. Then tag and return the holder object.

@Override

public Fragment getItem(int position) {

SuperCoolFragment superCoolFragment = new SuperCoolFragment();

superCoolFragment.setTag(YOUR_TAG);

return superCoolFragment;

}

来源:https://stackoverflow.com/questions/12384971/android-fragmentstatepageradapter-how-to-tag-a-fragment-to-find-it-later

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值