Question

I'm using default Activity in Android where you choose "Scrollable tabs + Swipe" as Navigation type. How can I determine which tab is currently showing, after sliding?

I tried it like this in class DummySectionFragment

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_starting_dummy,
                    container, false);
            TextView dummyTextView = (TextView) rootView
                    .findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(
                    ARG_SECTION_NUMBER)));


            switch(getArguments().getInt(ARG_SECTION_NUMBER))
            {
                case 1: // do something
                 ....
            }

but it's not working, becuase this method onCreateView is not being called always after sliding. I guess there is some easy way to do it, but I just can't find it. (also, it would be very good if it would be available for API 8)

Was it helpful?

Solution

To know when the page is being changed, you can use an OnPageChangeListener for the ViewPager. You can set this by using setOnPageChangeListener().

vpPager.setOnPageChangeListener(new OnPageChangeListener() {

    // This method will be invoked when a new page becomes selected.
    @Override
    public void onPageSelected(int position) {}

    // This method will be invoked when the current page is scrolled
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    // Called when the scroll state changes: 
    // SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
    @Override
    public void onPageScrollStateChanged(int state) {}
});

OTHER TIPS

Consider overiding the setUserVisibleHint() method in your fragment.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        Log.d(DEBUG_TAG, "Fragment is visiable");
        // do something you want
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top