Search code examples
androidandroid-viewpagerandroid-tablayout

How can I change the title of an android activity based on the Fragment in ViewPager2/TabView


I am working on an app and when I slide to the next tab I would like to change the title of the screen to match the Tab!


Solution

  • You can use registerOnPageChangeCallback in ViewPager2 to detect page swipes. In ViewPager2s host(for example host Activity) implement this event and when onPageSelected is called change the title of host Activity. In onPageSelected method you can get current position of ViewPager2 and based on position set your title.

    viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }
    
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
    
            // Set title of Activity based on the position of Fragment
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
            super.onPageScrollStateChanged(state);
        }
    });