Blnpwr
Blnpwr

Reputation: 1875

Android Tab name is disappearing when swiping

I started a new project on Android Studio using Tabbed Activity. I did not change any code but what I observed is, when you swipe between the tabs then the name of the current active tab is not showing. I want the name to be shown up always. How can I do this?

I post the default code which is delivered automatically by Android Studio. I think the method getPageTitle is responsible for this.

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.customerservice.R;

/**
 * A [FragmentPagerAdapter] that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 3;
    }
}

Upvotes: 1

Views: 189

Answers (1)

Ma Jeed
Ma Jeed

Reputation: 932

Open a new project

choose "Tabbed Activity" enter image description here

open "SectionsPagerAdapter" Java class:

enter image description here

enter image description here

Click on "Tab 1" and "Tab 2" enter image description here

you can see that the names of Tabs are stored in String resources you can find it here:

enter image description here

then you can change it for example: Hello Tab 1 Hello Tab 2 enter image description here

This is the result:

enter image description here enter image description here

Edited:

If you want to see all the tabs names at the same time, you can use "ViewPager2", read this documentation:

Create swipe views with tabs using ViewPager2

I hope this is helpful.

Upvotes: 1

Related Questions