marshallslee
marshallslee

Reputation: 655

Android: How to set tag to fragments in FragmentPagerAdapter?

Here's the inner class that contains fragments and changes fragment views on swipe. This class is defined in an Activity.

private class ViewPagerAdapter extends FragmentPagerAdapter {
    private int count;

    ViewPagerAdapter(FragmentManager fm, int count) {
        super(fm);
        this.count = count;
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                return new FriendsListFragment();

            case 1:
                Bundle bundle = new Bundle();
                bundle.putString(Keys.TAG, ChatListFragment.class.getSimpleName());
                ChatListFragment chatListFragment = new ChatListFragment();
                chatListFragment.setArguments(bundle);
                return chatListFragment;

            case 2:
                return new MoreFragment();

            default:
                return null;
        }
    }

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

Here I would like to add a code that sets tags to each fragment, so that I can recognize which fragment I'm at.

I searched quite much, and I haven't found a proper answer for this question, so please help.

Upvotes: 0

Views: 2087

Answers (1)

SpiralDev
SpiralDev

Reputation: 7331

You can override the setPrimaryItem method of your FragmentPagerAdapter.

 private class ViewPagerAdapter extends FragmentPagerAdapter {
        protected int currentPosition = -1;
        protected Fragment currentFragment;

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


        @Override
        public Fragment getItem(int position) {
           // ....
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
            this.currentPosition = position;
            if (object instanceof Fragment) {
                this.currentFragment = (Fragment) object;
            }
        }

        public int getCurrentPosition() {
            return currentPosition;
        }

        public Fragment getCurrentFragment() {
            return currentFragment;
        }
    }

Just use getCurrentPosition or getCurrentFragment methods to get information about current Fragment.

Upvotes: 2

Related Questions