Which lifecycle callback is called when a fragment

2019-09-03 11:37发布

问题:

I want to detect when a particular fragment of three fragments I have set up with a ViewPager comes on to screen. I have 3 fragments in the viewpager and have set up the viewpager with

mViewPager.setOffscreenPageLimit(2);

so all three fragments are constructed at once (since it stores 2 on each side). I checked that Fragment.onResume() is called just once and not when each fragment comes to the foreground. Is there another callback to ensure I can catch this event and send some analytics signal for it?

Thanks

回答1:

You can use the ViewPager.setOnPageChangeListener() to set a ViewPager.OnPageChangeListener().

Use the listener for the selected page based on its position in the PagerAdapter.

Here's my sample app:

package net.ynotapps.testviewpagerfragment;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class MainActivity extends ActionBarActivity {


    @InjectView(R.id.pager)
    ViewPager pager;

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

        ButterKnife.inject(this);

        CustomPagerAdapter adapter = new CustomPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                // Put Code here //

                // Example code //
                if (position == 2) {
                    Toast.makeText(MainActivity.this, "Found Position 2 fragment", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public static class CustomPagerAdapter extends FragmentPagerAdapter {

        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            CustomFragment fragment = new CustomFragment();
            Bundle bundle = new Bundle();
            bundle.putString("display_text", String.format("Fragment %d is here.", position));
            fragment.setArguments(bundle);
            return fragment;
        }

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

    public static class CustomFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            TextView tv = new TextView(getActivity());
            tv.setText(getArguments().getString("display_text"));
            return tv;
        }
    }
}


回答2:

ViewPager source code:

// Dispatch the change to any listeners
        if (mAdapterChangeListeners != null && !mAdapterChangeListeners.isEmpty()) {
            for (int i = 0, count = mAdapterChangeListeners.size(); i < count; i++) {
                mAdapterChangeListeners.get(i).onAdapterChanged(this, oldAdapter, adapter);
            }
        }

So, you can use the ViewPager.addOnAdapterChangeListener to listen the callback.