javaandroidandroid-layoutandroid-fragmentsandroid-titlebar

Change the title of the page along with the fragment Android


I think the problem is that:

        {
           ..
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
     ..
     this.setTitle("Home");

    }

and:

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            Home home = new Home();
            return Home;
        case 1:
            Mail mail = new Mail();
            return mail;
        default:
            return null;
    }
}

I would now like to show in place of the page title, the new Fragment setTitle

@Override
public Fragment getItem(int position) {

switch (position) {
    case 0:
        Home home = new Home();
        this.setTitle("change");  
        return Home;
    case 1:
        Mail mail = new Mail();
        this.setTitle("change");       
        return mail;
    default:
        return null;
}

I know that is not correct, but I do not know what the correct syntax is a whole day I'm trying to solve, but nothing. I would just change the title.


Solution

  • final ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Menu1");
        arrayList.add("Menu2");
        arrayList.add("Menu3");
        arrayList.add("Menu4");
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    
            @Override
            public void onPageSelected(int position) {
                getSupportActionBar().setTitle(arrayList.get(position));
            }
    
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
    
            }
    
            @Override
            public void onPageScrollStateChanged(int pos) {
                // TODO Auto-generated method stub
    
            }
        });