Fragment onResume() isn't called when using FragmentPagerAdapter

一个人想着一个人 提交于 2019-12-09 06:35:18

问题


I need my fragments to always call a certain function when they are the active fragment, so I put it in onResume(), but it isn't being called.

Fragment A

@Override
public  void onResume(){
    super.onResume();
    Log.d("clear state", " "+clear);
    if(clear == true)
    {
        restart();
        clear = false;
        calculate();
    }
}

I use a FragmentPagerAdapter with a ViewPager to switch fragments

public class ScoutingFragSingle extends FragmentPagerAdapter{


@Override
public Fragment getItem(int index) {
    Bundle data = new Bundle();
    switch(index){
    case 0:
        TeamsFragment teamsFragment = new TeamsFragment();
        data.putInt("current_page", index+1);
        teamsFragment.setArguments(data);
        return teamsFragment;
    case 1:

        data.putInt("current_page", index+1);
        data.putInt("matchId", matchNum);
        aFragment.setArguments(data);
        return aFragment;

So how would I make the fragments call their onResume()?


回答1:


I had the same problem while ago.

Create a new interface and implement it by both of your Fragments:

public interface OnPageSelectedListener {
    void onPageSelected();
}

In parent activity implement android.support.v4.view.ViewPager.OnPageChangeListener and call Fragment method like this:

@Override
public void onPageSelected(int i) {
    OnPageSelectedListener fragment = (OnPageSelectedListener ((PlaceListPagerAdapter)pager.getAdapter()).getFragment(i);
    fragment.onPageSelected();
}

PS: Name of the new interface and its method is a bit confusing, so be careful or change it.




回答2:


Override Fragment.setUserVisibleHint. When setUserVisibleHint is true call same logic you use for onResume.

You can see when FragmentPagerAdapter calls setUserVisibleHint in instantiateItem and setPrimaryItem. Applicable to android since 4.2.1 and support-v4.



来源:https://stackoverflow.com/questions/15463116/fragment-onresume-isnt-called-when-using-fragmentpageradapter

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