Skip to content

Instantly share code, notes, and snippets.

@jacek-marchwicki
Created June 18, 2014 10:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jacek-marchwicki/d6320ba9a910c514424d to your computer and use it in GitHub Desktop.
Save jacek-marchwicki/d6320ba9a910c514424d to your computer and use it in GitHub Desktop.
ViewPager with getActiveFragment for position
package com.yapert.view.viewpager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import com.google.common.base.Charsets;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
public class SmartViewPager extends ViewPager {
@SuppressWarnings("UnusedDeclaration")
public SmartViewPager(Context context) {
super(context);
}
@SuppressWarnings("UnusedDeclaration")
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;
}
}
@georgikoemdzhiev
Copy link

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