I need to assign a unique tab id to my tabs created using viewpager and tablayout?

后端 未结 3 1532
清酒与你
清酒与你 2021-01-11 23:59

I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.

What I need is to assign differe

3条回答
  •  礼貌的吻别
    2021-01-12 00:34

    In your viewPager Adapter extends FragmentPagerAdapter this and include these methods and it will give new ID to every Fragment and when you add manually data in array and call notifyDataSetChange(), also call this method notifyChangeInPosition(mItems.size() - 1);.

    From this the added item get a new ID.

      private long baseId = 0;
    
        ViewPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }
    
        // Returns total number of pages
        @Override
        public int getCount() {
            return mItems.size();
        }
    //this is called when notifyDataSetChanged() is called
        @Override
        public int getItemPosition(Object object) {
            // refresh all fragments when data set changed
            return PagerAdapter.POSITION_NONE;
        }
    
        @Override
        public long getItemId(int position) {
            // give an ID different from position when position has been changed
            return baseId + position;
        }
    
        /**
         * Notify that the position of a fragment has been changed.
         * Create a new ID for each position to force recreation of the fragment
         *
         * @param n number of items which have been changed
         */
        void notifyChangeInPosition(int n) {
            // shift the ID returned by getItemId outside the range of all previous fragments
            baseId += getCount() + n;
        }
    

提交回复
热议问题