Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ViewPager with getActiveFragment for position
package com.yapert.view.viewpager;
import android.content.Context;
import android.util.AttributeSet;
public class SmartViewPager extends ViewPager {
public SmartViewPager(Context context) {
public SmartViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
public Fragment getActiveFragment(FragmentManager fragmentManager, int position) {
final String name = makeFragmentName(getId(), position);
final Fragment fragmentByTag = fragmentManager.findFragmentByTag(name);
if (fragmentByTag == null) {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
fragmentManager.dump("", null, new PrintWriter(outputStream, true), null);
final String s = new String(outputStream.toByteArray(), Charsets.UTF_8);
throw new IllegalStateException("Could not find fragment via hacky way.\n" +
"We were looking for position: " + position + " name: " + name + "\n" +
"Fragment at this position does not exists, or hack stopped working.\n" +
"Current fragment manager dump is: " + s);
return fragmentByTag;
private static String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;

This comment has been minimized.

Copy link

@georgikoemdzhiev georgikoemdzhiev commented Dec 14, 2015

Hello, what is the output of Charsets.UTF_8? :)

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