Created
October 1, 2013 14:20
-
-
Save ikew0ng/6779232 to your computer and use it in GitHub Desktop.
获取ViewPager特定位置的Fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v4.app.Fragment; | |
import android.support.v4.app.FragmentManager; | |
import android.support.v4.app.FragmentStatePagerAdapter; | |
import android.support.v4.view.ViewPager; | |
/** | |
* Created by Chaojun Wang on 5/6/14. | |
*/ | |
public class ViewPagerUtils { | |
private ViewPagerUtils() {} | |
/** | |
* Find fragment in certain position of viewpager. | |
* | |
* @param fragmentManager | |
* @param viewPager | |
* @param position | |
* @return The Fragment if found or null otherwise. | |
*/ | |
public static Fragment findFragment(FragmentManager fragmentManager, ViewPager viewPager, | |
int position) { | |
return fragmentManager.findFragmentByTag(makeFragmentName(viewPager.getId(), position)); | |
} | |
private static String makeFragmentName(long viewPagerId, int position) { | |
return "android:switcher:" + viewPagerId + ":" + position; | |
} | |
/** | |
* Find fragment in certain position of viewpager. | |
* | |
* @param adapter {@link android.support.v4.app.FragmentStatePagerAdapter} of this ViewPager | |
* @param viewPager | |
* @param position | |
* @return The Fragment if found or null otherwise. | |
*/ | |
public static Object findFragment(FragmentStatePagerAdapter adapter, ViewPager viewPager, | |
int position) { | |
return adapter.instantiateItem(viewPager, position); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
可以定义一个BaseFragmentPagerAdapter extends FragmentPagerAdapter
子FragmentPagerAdapter Override getTag方法
BaseFragmentPagerAdapter Override instantiateItem方法,mCurTransaction.add(container.getId(), fragment, getTag(position));
这样子FragmentPagerAdapter可以这样拿Fragment
public Fragment findFragment(FragmentManager fm, String tag) {
return fm.findFragmentByTag(tag);
}