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;
}
}
Open a new project
open "SectionsPagerAdapter" Java class:
you can see that the names of Tabs are stored in String resources you can find it here:
then you can change it for example: Hello Tab 1 Hello Tab 2
This is the result:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.