Skip to content

Instantly share code, notes, and snippets.

@ikew0ng
Created October 1, 2013 14:20
Show Gist options
  • Save ikew0ng/6779232 to your computer and use it in GitHub Desktop.
Save ikew0ng/6779232 to your computer and use it in GitHub Desktop.
获取ViewPager特定位置的Fragment
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);
}
}
@hanji1122
Copy link

可以定义一个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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment