Search code examples
androidandroid-viewpagerfragmentstatepageradapter

How to initialize my ViewPager


I have an Activity A which contains a list and an Activity B which displays the detail of an item from activity A using a fragment. There is a ViewPager in Activity B, which allows me to swipe left and right to view different item details in the list. The problem is where and how to initialize Activity B to display the details of the item I clicked in Activity A?

Below is my FragmentStatePagerAdapter class, currently no matter which item i clicked in activity A, it always launches the first item (though the swiping function is working)

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        Cursor data;
        ArticleDetailUpdateFragment detailUpdateFragment;

        public ScreenSlidePagerAdapter(FragmentManager fm, Cursor data) {
            super(fm);
            this.data = data;

            detailUpdateFragment = new ArticleDetailUpdateFragment();
            long id = getIntent().getLongExtra(ArticleListActivity.EXTRA_ITEM_ID, -1);
            Log.d(TAG, "the itemId received in detail activity: " + String.valueOf(id));
            detailUpdateFragment.setId(id);

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.pager, detailUpdateFragment).commit();
        }

        @Override
        public Fragment getItem(int position) {
            detailUpdateFragment = new ArticleDetailUpdateFragment();
            data.moveToPosition(position);
            long id = data.getLong(data.getColumnIndex(ItemsContract.Items._ID));
            detailUpdateFragment.setId(id);

            return detailUpdateFragment;
        }

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

Solution

  • You will have to get the position of the item clicked, assuming it is a recycler view, you can get the position by using this method

    viewholder.getAdapterPosition()
    

    Next you will have to pass this position in activityB using intent and set the viewpager's current item as this position after you have attached an adapter to your viewpager

    viewpager.setCurrentItem(position, false)
    

    We pass in false because we dont want animation in the beginning