如何使用书法为android.support.design.widget.TabLayout自定义字体

时间:2016-08-20 18:57:39

标签: android fonts android-support-library android-custom-view android-tablayout

我使用书法来自定义我的应用字体... 我的应用包含android.support.design.widget.TabLayout ... 我的应用程序的字体已更改,除了tabLayout标题和TabLayout中的标签标题使用设备字体而不是自定义字体。 标签有文字和图标。我有标题和tabIcons数组的mFragmentTitleList数组... 我试图按照这里解释的方式使用风格和主题:calligraphy 但他们都没有工作......

1 个答案:

答案 0 :(得分:0)

回答是使用自定义视图...我已经为每个选项卡应用了自定义XML布局...为了实现这一点,应该在将滑动选项卡附加到寻呼机后迭代所有TabLayout.Tabs:

// Get the ViewPager and set it's PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    MyFragmentPagerAdapter pagerAdapter = 
        new MyFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
    viewPager.setAdapter(pagerAdapter);

    // Give the TabLayout the ViewPager
    TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);

    // Iterate over all tabs and set the custom view
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = tabLayout.getTabAt(i);
        tab.setCustomView(pagerAdapter.getTabView(i));
    }

接下来我们应该将getTabView(position)方法添加到MyFragmentPagerAdapter类中:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[] { "Tab1", "Tab2","Tab3" };
 private int[] tabIcons = {
        R.drawable.ic_one,
        R.drawable.ic_two,
        R.drawable.ic_three
};

public View getTabView(int position) {
    // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
    View view= LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
    TextView textView= (TextView) view.findViewById(R.id.textView);
    textView.setText(getPageTitle(position));
    ImageView imageView = (ImageView) view.findViewById(R.id.imgView);
    imageView .setImageResource(tabIcons[position]);
    return view;
}

}

这是自定义视图的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="New Text"
    android:gravity="center"
    android:textColor="@drawable/sel_tab_text"
    android:id="@+id/textView" />