Alternative for the onResume() during Fragment switching

旧城冷巷雨未停 提交于 2019-11-26 15:35:30

问题


onResume() method won't get called when we switch between fragments more than one time. So, is there any better way to handle resume operation?


回答1:


Code follows:

Step: 1

Create Interface:

public interface YourFragmentInterface {
    void fragmentBecameVisible();
}

Step: 2

Attach Listner In setOnPageChangeListener:

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(final int position, final float v, final int i2) {
        }

        @Override
        public void onPageSelected(final int position) {
            YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position);
            if (fragment != null) {
                fragment.fragmentBecameVisible();
            } 
        }

        @Override
        public void onPageScrollStateChanged(final int position) {
        }
    });

Step: 3

Implement Interface In Your Fragment:

public class yourActivity extends SherlockFragment implements YourFragmentInterface{
    @Override
    public void fragmentBecameVisible() {
          System.out.println("TestFragment");
    }
}

Implement this listner in all yor fragment activity fragmentBecameVisible() this method call during Fragment switching.

Thanks.




回答2:


I think, I have found the answer. Here is the link which will force onResume() of the fragment to be called every time the fragment becomes visible.
Fragments onResume from back stack




回答3:


You could do resume work by provide a public method on every fragment when page selected, I give you a example:

public class MainActivity extends FragmentActivity {
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;

private ArrayList<Fragment> mFragments;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

    mFragments = new ArrayList<Fragment>();
    mFragments.add(new TestFragment1());
    mFragments.add(new TestFragment2());
    mFragments.add(new TestFragment3());

    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment1").setIndicator("fragment1"));
    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment2").setIndicator("fragment2"));
    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment3").setIndicator("fragment3"));

    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tab", mTabHost.getCurrentTabTag());
}

private void refreshPage(int i) {
    Fragment fragment = mFragments.get(i);

    switch (i) {
        case 0:
            ((TestFragment1) fragment).refreshView();
            break;
        case 1:
            ((TestFragment2) fragment).refreshView();
            break;
        case 2:
            ((TestFragment3) fragment).refreshView();
            break;
    }
   }

class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener,
        ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;

    public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mTabHost = tabHost;
        mViewPager = pager;
        mTabHost.setOnTabChangedListener(this);
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(TabHost.TabSpec tabSpec) {
        tabSpec.setContent(new DummyTabFactory(mContext));
        mTabHost.addTab(tabSpec);
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int i) {
        return mFragments.get(i);
    }

    @Override
    public void onPageScrolled(int i, float v, int i2) {
    }

    @Override
    public void onPageSelected(int i) {
        TabWidget widget = mTabHost.getTabWidget();
        int oldFocusability = widget.getDescendantFocusability();
        widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        mTabHost.setCurrentTab(i);
        widget.setDescendantFocusability(oldFocusability);
        refreshPage(i);
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }

    @Override
    public void onTabChanged(String s) {
        int postion = mTabHost.getCurrentTab();
        mViewPager.setCurrentItem(postion, true);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    class DummyTabFactory implements TabHost.TabContentFactory {
        private final Context mContext;

        public DummyTabFactory(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String s) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }
}
}

and then you write your Fragment like this:

public class TestFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.main, container, false);
}

public void refreshView() {
    //do whatever you want
}
}



回答4:


You can simply simulate onResume() for each fragment by using an interface!!!

1- create an interface named FragmentLifecycle , the code is as follows:

public interface FragmentLifecycle {
   public void onResumeFragment();
}

2- Let each Fragment implement the interface:

public class FragmentOne extends Fragment implements FragmentLifecycle

3- Implement interface methods in each fragment:

@Override
public void onResumeFragment() {
  Log.i(TAG, "onResumeFragment()");
  Toast.makeText(getActivity(), "onResumeFragment():" + TAG,Toast.LENGTH_SHORT).show(); 
}

4- Call interface methods on ViewPager page change:

viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            FragmentLifecycle fragmentToShow = (FragmentLifecycle)adapter.getItem(position);
            fragmentToShow.onResumeFragment();
        }
    });

Enjoy!




回答5:


You can try this,

Step1: Override the Tabselected method in your activity

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    try {
    if(MyEventsFragment!=null && tab.getPosition()==3)
    {
        MyEvents.fragmentChanged();
    }
    }
    catch (Exception e)
    {

    }
    mViewPager.setCurrentItem(tab.getPosition());
}

Step 2: Using static method do what you want in your fragment,

public static void fragmentChanged()
{
    Toast.makeText(actvity, "Fragment Changed", Toast.LENGTH_SHORT).show();
}



回答6:


I have solved this problem using fragment Override method :

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        if (getView() != null) {
            // your code goes here
        }
    }
}

Note: In the Viewpager first fragment setUserVisibleHint called before onCreateView so you need to handle this.

handle setUserVisibleHint called before onCreateView in Fragment



来源:https://stackoverflow.com/questions/17845641/alternative-for-the-onresume-during-fragment-switching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!