Search code examples
androidandroid-fragmentsandroid-activityback-button

How to call a fragment function on pressing back button from a child activity in android


I have a main activity which has tabbed fragments implemented via FragmentPagerAdapter. From one of the fragments, I open a new activity(which has its home button set). I press the home button to return to the main activity(with fragments). At this point, I want to be able to recreate the fragments screens. What is the function that is called at this point?

I came to know that the main activity's onRestart() will be called. In this function, I tried to call a method of the fragment using:

ExampleFragment myFragment = (ExampleFragment) mPagerAdapter.getItem(0).<myDesiredMethod>();

Here, I am getting the issue that myFragment is getting the fragment's variables, but they are all null. They aren't initialized, just like they were when the new (child) activity was spawned.

How can I recreate the fragment screen on exiting a child activity?

Thanks.


Solution

  • To answer your Title question, use the following code in your FragmentPagerAdapter.

    private FirstFragment mFirstFragment;
    private SecondFragment mSecondFragment
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        switch(position) {
            case 0:
                mFirstFragment = (FirstFragment)super.instantiateItem(container, position);
                return mFirstFragment;
            case 1:
                mSecondFragment = (SecondFragment)super.instantiateItem(container, position);
    
                return mSecondFragment;
        }
        return super.instantiateItem(container, position);
    }
    
    public boolean isFragmentInstantiated(int position) {
        switch(position) {
            case 0:
                if(mFirstFragment != null)
                    return true;
                break;
            case 1:
                if(mSecondFragment != null)
                    return true;
                break;
    
        }
        return false;
    }
    
    public void doSomethingOnFirstFragment() {
        if(isFragmentInstantiated(0) {
            mFirstFragment.doYaThang();
        }
    }
    

    This way, you can call Fragment methods by calling the adapter's doSomethingOnFirstFragment() from the Activity.