Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8818989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:14:27+00:00 2026-06-14T05:14:27+00:00

I have an Activity containing some Fragment s in a ViewPager . Here is

  • 0

I have an Activity containing some Fragments in a ViewPager. Here is the adapter (the mFooFragment‘s are members of the Activity.

private class HomePagerAdapter extends FragmentPagerAdapter
{
    public HomePagerAdapter(FragmentManager fm)
    {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {
        switch (position)
        {
        case 0:
            mSellingFragment = new SellingFragment();
            return mSellingFragment;
        case 1:
            mSearchFragment = new SearchFragment();
            return mSearchFragment;
        case 2:
            mProfileFragment = new ProfileFragment();
            return mProfileFragment;
        }
        return null;
    }

    @Override
    public int getCount()
    {
        return 3;
    }
}

And then I later do stuff like:

mSellingFragment.refresh();

Unfortunately, the member fragments can be null. One case I am ok with and can check for – the pages are lazily loaded so they are not available until they are shown. But that is ok, I only want refresh() to act on the visible page.

But sometimes they are null even when visible. I think what is happening is this:

My fragments have setRetainInstance(true) so when I navigate away from the activity it is destroyed but the fragments are retains, and then when I go back to it, the activity is recreated with the old fragments somehow, and getItem() is never called, so mFooFragment is never set.

Is that right? How exactly is one supposed to handle this? One way I can think of is adding a load of setFooFragment(FooFragment f) { mFooFragment = f; } functions to the Activity and calling them from FooFragment.onAttach() but there must be a better way!

Edit

I looked up the source code of FragmentPagerAdapter (often the only way to get answers in Android-land!) and it is indeed the case that it saves the fragments:

@Override
public Object instantiateItem(View container, int position) {
    if (mCurTransaction == null) {
        mCurTransaction = mFragmentManager.beginTransaction();
    }

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), position);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);
    if (fragment != null) {
        if (DEBUG) Log.v(TAG, "Attaching item #" + position + ": f=" + fragment);
        mCurTransaction.attach(fragment);
    } else {
        fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        mCurTransaction.add(container.getId(), fragment,
                makeFragmentName(container.getId(), position));
    }
    if (fragment != mCurrentPrimaryItem) {
        fragment.setMenuVisibility(false);
    }

    return fragment;
}

Unfortunately it doesn’t make those reattached Fragments available to subclasses!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:14:28+00:00Added an answer on June 14, 2026 at 5:14 am

    My current, slightly hacky solution is to make a copy of FragmentPagerAdapter and add a handler for when fragments are added: void onItemCreated(Fragment fragment, int position) which you can then override in your custom pager adapter to save the fragments as member variables. Complete code below (NOT TESTED YET!)

    /*
     * Copyright (C) 2011 The Android Open Source Project
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.your.package.name;
    
    import android.os.Parcelable;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.PagerAdapter;
    import android.util.Log;
    import android.view.View;
    import android.view.ViewGroup;
    
    /**
     * Implementation of {@link android.support.v4.view.PagerAdapter} that
     * represents each page as a {@link Fragment} that is persistently
     * kept in the fragment manager as long as the user can return to the page.
     *
     * <p>This version of the pager is best for use when there are a handful of
     * typically more static fragments to be paged through, such as a set of tabs.
     * The fragment of each page the user visits will be kept in memory, though its
     * view hierarchy may be destroyed when not visible.  This can result in using
     * a significant amount of memory since fragment instances can hold on to an
     * arbitrary amount of state.  For larger sets of pages, consider
     * {@link FragmentStatePagerAdapter}.
     *
     * <p>When using FragmentPagerAdapter the host ViewPager must have a
     * valid ID set.</p>
     *
     * <p>Subclasses only need to implement {@link #getItem(int)}
     * and {@link #getCount()} to have a working adapter.
     *
     * <p>Here is an example implementation of a pager containing fragments of
     * lists:
     *
     * {@sample development/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentPagerSupport.java
     *      complete}
     *
     * <p>The <code>R.layout.fragment_pager</code> resource of the top-level fragment is:
     *
     * {@sample development/samples/Support4Demos/res/layout/fragment_pager.xml
     *      complete}
     *
     * <p>The <code>R.layout.fragment_pager_list</code> resource containing each
     * individual fragment's layout is:
     *
     * {@sample development/samples/Support4Demos/res/layout/fragment_pager_list.xml
     *      complete}
     */
    public abstract class FragmentPagerAdapter extends PagerAdapter {
        private static final String TAG = "FragmentPagerAdapter";
        private static final boolean DEBUG = false;
    
        private final FragmentManager mFragmentManager;
        private FragmentTransaction mCurTransaction = null;
        private Fragment mCurrentPrimaryItem = null;
    
        public FragmentPagerAdapter(FragmentManager fm) {
            mFragmentManager = fm;
        }
    
        /**
         * Return the Fragment associated with a specified position.
         */
        public abstract Fragment getItem(int position);
    
        @Override
        public void startUpdate(ViewGroup container) {
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
    
            final long itemId = getItemId(position);
    
            // Do we already have this fragment?
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = mFragmentManager.findFragmentByTag(name);
            if (fragment != null) {
                if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
                mCurTransaction.attach(fragment);
            } else {
                fragment = getItem(position);
                if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
                mCurTransaction.add(container.getId(), fragment,
                        makeFragmentName(container.getId(), itemId));
            }
            if (fragment != mCurrentPrimaryItem) {
                fragment.setMenuVisibility(false);
                fragment.setUserVisibleHint(false);
            }
    
            onItemCreated(fragment, position);
            return fragment;
        }
    
        /**
         * Called when a fragment has been created/attached.
         */
        public abstract void onItemCreated(Fragment fragment, int position);
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object
                    + " v=" + ((Fragment)object).getView());
            mCurTransaction.detach((Fragment)object);
        }
    
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            Fragment fragment = (Fragment)object;
            if (fragment != mCurrentPrimaryItem) {
                if (mCurrentPrimaryItem != null) {
                    mCurrentPrimaryItem.setMenuVisibility(false);
                    mCurrentPrimaryItem.setUserVisibleHint(false);
                }
                if (fragment != null) {
                    fragment.setMenuVisibility(true);
                    fragment.setUserVisibleHint(true);
                }
                mCurrentPrimaryItem = fragment;
            }
        }
    
        @Override
        public void finishUpdate(ViewGroup container) {
            if (mCurTransaction != null) {
                mCurTransaction.commitAllowingStateLoss();
                mCurTransaction = null;
                mFragmentManager.executePendingTransactions();
            }
        }
    
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return ((Fragment)object).getView() == view;
        }
    
        @Override
        public Parcelable saveState() {
            return null;
        }
    
        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }
    
        /**
         * Return a unique identifier for the item at the given position.
         *
         * <p>The default implementation returns the given position.
         * Subclasses should override this method if the positions of items can change.</p>
         *
         * @param position Position within this adapter
         * @return Unique identifier for the item at position
         */
        public long getItemId(int position) {
            return position;
        }
    
        private static String makeFragmentName(int viewId, long id) {
            return "android:switcher:" + viewId + ":" + id;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an activity MyActivity that extends from MapActivity. In the .xml file containing
I have an Activity containing an ImageView and I'd like to allow the User
I'm trying to create DatePicker dialog from a class that doesn't extends the Activity
I am building custom activities, First activity is containing ReceiveSendReply activity with some other
Let's say I have an Activity which displays a View containing a TextView .
I have an Activity which is basically a big webview with some other buttons.
In my android application I have an activity containing a Parcelable object (implements Parcelable
I am having some problems with an alertdialog box. I have a listview containing
I have an Activity with a layout containing a custom ImageView and a few
I have an activity group containing 3 activities. When a button is pressed, I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.