ziky90 ziky90 - 3 months ago 62x
Android Question

Android getting fragment that is in FragmentPagerAdapter

I have following problem:
I have one activity in which I have two tabs which are made both as fragments using FragmentPagerAdapter
In some moment I would like to change View of one of these fragments, but I am not able to findFragmentById() or findFragmentByTag() I am unable to set id, because I am not declaring Fragment in XML, because of the FragmentPagerAdapter
And when I am trying to set tag I am getting following problem:

08-15 21:46:23.805: E/AndroidRuntime(9297): java.lang.IllegalStateException: Can't change tag of fragment Companies{416d7b78 id=0x7f04002e companies}: was companies now android:switcher:2130968622:1

My code of the pager FragmentPagerAdapter:

public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final FragmentActivity mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

final class TabInfo {
private final Class<?> clss;
private final Bundle args;

TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;

public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;

public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);

public int getCount() {
return mTabs.size();

public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
FragmentTransaction ft=mContext.getSupportFragmentManager().beginTransaction();
Fragment fragment=Fragment.instantiate(mContext, info.clss.getName(), info.args);

ft.add(mViewPager.getId(), fragment, "companies");
ft.add(mViewPager.getId(), fragment);
Log.v("FRAGMENT ID", "fragment tag: "+fragment.getTag());
Log.v("FRAGMENT ID", "fragment tag: "+fragment.getTag());
return fragment;

public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

public void onPageSelected(int position) {
new Thread(new Runnable() {

public void run() {



public void onPageScrollStateChanged(int state) {

public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {


public void onTabUnselected(Tab tab, FragmentTransaction ft) {


public void onTabReselected(Tab tab, FragmentTransaction ft) {

Thank you in advance for your answers.


The Fragments supplied by the FragmentPagerAdapter are auto-tagged when they're instantiated. You can retrieve the tag with this method:

private static String makeFragmentName(int viewPagerId, int index) {
     return "android:switcher:" + viewPagerId + ":" + index;

Reference: reusing fragments in a fragmentpageradapter