Change the title of the tab in a fragment activity

5.3k Views Asked by At

I want to change the title of a tab in a tabbed activity. Currently with the below code I could switch to the tab, but unable to change the tab title on notification arrival.

How can I change the title of the tab.

ViewPager viewPager = (ViewPager) AllTabs.mViewPager.findViewById(R.id.container);
                    int currentTab = viewPager.getCurrentItem();
                    viewPager.setCurrentItem(1);

Above code is helping to change or switch to mytab. Try code below to check the title of a tab

PagerAdapter pagerAdapter = new PagerAdapter() {
                            @Override
                            public int getCount() {
                                return 0;
                            }

                            @Override
                            public boolean isViewFromObject(View view, Object object) {
                                return false;
                            }
                        };
                        Log.e("ServerManager_Title",pagerAdapter.getPageTitle(1).toString());
                        pagerAdapter.notifyDataSetChanged();

but as the pagerAdapter is not associated with any tab its throwing NullPointerException on calling any method.

12-22 11:27:37.049 20448-20448/com.moodoff E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.moodoff, PID: 20448
                                                             java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
                                                                 at com.moodoff.helper.ServerManager$3.run(ServerManager.java:199)
                                                                 at android.os.Handler.handleCallback(Handler.java:815)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                 at android.os.Looper.loop(Looper.java:207)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5776)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

My Codes: In ServerManager.java file

final Activity currActivity = (Activity)context;
        NotificationCompat.Builder builder =
            new NotificationCompat.Builder(currActivity)
                    .setSmallIcon(R.drawable.btn_dedicate)
                    .setColor(001500)
                    .setContentTitle("MoodOff")
                    .setContentText(UserDetails.getUserName()+ "!! You got new notifications!!");

        Intent notificationIntent;
        if(currActivity==null){
            notificationIntent = new Intent(currActivity, Start.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        }
        else{
            currActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //Toast.makeText(context,"Hi New one",Toast.LENGTH_SHORT).show();
                    //designNotPanel(1);
                    ViewPager viewPager = (ViewPager) AllTabs.mViewPager.findViewById(R.id.container);
                    int currentTab = viewPager.getCurrentItem();
                    viewPager.
                    viewPager.getAdapter().notifyDataSetChanged();

                }
            });
            notificationIntent = new Intent(currActivity, NotificationFragment.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(currActivity, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);
        builder.setAutoCancel(true);
}

In AllTabs.java which hosts all the tabs or is the main activity which has all the tabs public class AllTabs extends AppCompatActivity implements ViewPager.OnPageChangeListener{

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
//private ViewPager mViewPager;
public static ViewPager mViewPager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_all_tabs);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    //Request all the dangerous permissions over here

}

@Override
public void onPageScrollStateChanged(int state) {

}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

Ami doing the correct way? On the arrival of notifications i want to display a count(a number) on my second tab(doesn't matter in which tab i am out of the three tabs i have) that number is dynamic and so once the notification appears i need to count that and display i.e. change the title of the second tab to a new title based on the dynamic count.

2

There are 2 best solutions below

3
On

1.activity should implement an OnPageChangeListener

2.create your ViewPager

3.you can use viewPager.setOnPageChangeListener(this)

4.

@Override
        public abstract void onPageSelected(int position) {
            setTitle(getTitleFromPosition(position));
        }

then pagerAdapter.getPageTitle(1).toString() won't be null

See here

if ViewPager.setOnPageChangeListener not working because it is deprecated now use ViewPager.addOnPageChangeListener instead.

for example,

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
0
On

As @Charuka that is also possible and you can do this way also.

viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);

tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

This is you method to setup you ViewPager Adapter.

private void setupViewPager(ViewPager viewPager)
{
    try
    {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new FragmentGeneral(), "GENERAL");
        adapter.addFrag(new FragmentInterests(), "INTERESTS");
        adapter.addFrag(new FragmentAlert(), "ALERTS");
        adapter.addFrag(new FragmentSocial(), "SOCIAL");
        viewPager.setAdapter(adapter);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

Now create ViewPagerAdapter class which is handle you fragment and Tab title

private class ViewPagerAdapter extends FragmentPagerAdapter
    {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

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

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {

            //here you can set your custom title by using position 
            if (position==1)
                return "Title";
            else
                return mFragmentTitleList.get(position);
        }
    }

For more detail please check this and this .