带有android.support.design.widget.TabLayout的多行PageTitle

时间:2017-12-08 10:34:57

标签: android android-fragments android-tablayout

在Android应用中,我使用TabLayout在单个活动中显示多个Fragments。 我希望标签上标有图标和两行标题。

在活动的创建中,我初始化SectionsPageAdapterTabLayout,如:

private SectionsPagerAdapter mSectionsPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
    ...
    // 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);
    // add a PageChangeListener to be able to detect which tab is activated
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
        ...
    });

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

    //Set icons for tabs
    tabLayout.getTabAt(0).setIcon(R.drawable.ic0);
    tabLayout.getTabAt(1).setIcon(R.drawable.ic1);
    tabLayout.getTabAt(2).setIcon(R.drawable.ic2);
}

SectionpagerAdapter我使用以下内容定义 PageTitles

public CharSequence getPageTitle(int position) {
    switch (position) {
        case 0:
            return "First \nTab";
        case 1:
            return "Second \nTab";
        case 2:
            return "Third \nTab";
    }
    return null;
}

但是当我运行该应用时, PageTitles 并没有分成两行,而是缩短为......以适应屏幕。

如何为标签启用多行 PageTitles

1 个答案:

答案 0 :(得分:0)

tabLayout.getTabAt(i).setCustomView(yuorTabView);

您可以自定义自己的TabView