Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android设计支持库中将书法与TabLayout一起用于xml中的自定义字体?_Android_Fonts_Androiddesignsupport - Fatal编程技术网

如何在Android设计支持库中将书法与TabLayout一起用于xml中的自定义字体?

如何在Android设计支持库中将书法与TabLayout一起用于xml中的自定义字体?,android,fonts,androiddesignsupport,Android,Fonts,Androiddesignsupport,如何使用书法将自定义字体应用于设计支持库中的表格布局 我已经让它在java中工作,大多数答案似乎都提到了java。 (例如) 我不想做自定义类,我只想用书法。 () 如果我为tabTextAppearance使用自定义样式,我可以更改textSize,但fontPath没有任何效果 谢谢有一种方法可以将xml中的自定义字体用于表格布局,但它有点不成熟。您必须为选项卡提供自己的自定义布局,在该布局中,您可以随心所欲地设置文本视图的样式 因此,基本上您需要进行以下设置: public class

如何使用书法将自定义字体应用于设计支持库中的表格布局

我已经让它在java中工作,大多数答案似乎都提到了java。 (例如)

我不想做自定义类,我只想用书法。 ()

  • 如果我为tabTextAppearance使用自定义样式,我可以更改textSize,但fontPath没有任何效果

谢谢

有一种方法可以将xml中的自定义字体用于表格布局,但它有点不成熟。您必须为选项卡提供自己的自定义布局,在该布局中,您可以随心所欲地设置文本视图的样式

因此,基本上您需要进行以下设置:

public class MainActivity extends AppCompatActivity {

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

    // Get the ViewPager and set it's PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    SampleFragmentPagerAdapter pagerAdapter = 
        new SampleFragmentPagerAdapter(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));
    }
}

//...
}
这是custom_tab.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    fontPath="fonts/CustomFont.otf"
    tools:ignore="MissingPrefix" />

代码中缺少了一些东西,但我认为您可以填充缺少的部分,这只是其中的要点。这只是参考文献中博客文章的一部分,还添加了书法。您可以查看它以了解更多详细信息

参考文献:


您可以为android.support.design.widget.TabLayout定义样式,然后为文本外观编写自己的样式,如下所示:

<style name="TextAppearance.FontPath" parent="android:TextAppearance">
<item name="fontPath">fonts/Roboto-Light.ttf</item>

字体/Roboto-Light.ttf

然后您必须添加以下项目:

<item name="tabTextAppearance">@style/TextAppearance.FontPath</item>
@style/TextAppearance.FontPath

符合您的android.support.design.widget.TabLayout风格。它应该可以工作。

我使用了扩展表格布局的方法。通过这种方式,您可以简单地在TabLayout中定义fontPath

<com.mypackage.base.widget.FontAwareTabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        fontPath="@string/common_fonts_sans_condensed_bold"
/>

下面是类别代码:

 /**
 * Simple helper class which extends a TabLayout to allow us to customize the font of the tab.
 * https://gist.github.com/tmtrademarked/09926077a406959be15fc8a824a52751
 * https://github.com/chrisjenx/Calligraphy/issues/180
 */
public final class FontAwareTabLayout extends TabLayout {

  private String fontPath;

  public FontAwareTabLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    fontPath = pullFontPathFromView(context, attrs, new int[] { R.attr.fontPath });
  }

  /**
   * Tries to pull the Custom Attribute directly from the TextView.
   *
   * @param context Activity Context
   * @param attrs View Attributes
   * @param attributeId if -1 returns null.
   * @return null if attribute is not defined or added to View
   */
  static String pullFontPathFromView(Context context, AttributeSet attrs, int[] attributeId) {
    if (attributeId == null || attrs == null) return null;

    final String attributeName;
    try {
      attributeName = context.getResources().getResourceEntryName(attributeId[0]);
    } catch (Resources.NotFoundException e) {
      // invalid attribute ID
      return null;
    }

    final int stringResourceId = attrs.getAttributeResourceValue(null, attributeName, -1);
    return stringResourceId > 0 ? context.getString(stringResourceId)
        : attrs.getAttributeValue(null, attributeName);
  }

  @Override
  public void addTab(@NonNull Tab tab, int position, boolean setSelected) {
    super.addTab(tab, position, setSelected);

    ViewGroup mainView = (ViewGroup) getChildAt(0);
    ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
    int tabChildCount = tabView.getChildCount();
    for (int i = 0; i < tabChildCount; i++) {
      View tabViewChild = tabView.getChildAt(i);
      if (tabViewChild instanceof TextView) {
        CalligraphyUtils.applyFontToTextView(getContext(), (TextView) tabViewChild, fontPath);
      }
    }
  }
}
/**
*简单的助手类,它扩展了TabLayout,允许我们自定义选项卡的字体。
* https://gist.github.com/tmtrademarked/09926077a406959be15fc8a824a52751
* https://github.com/chrisjenx/Calligraphy/issues/180
*/
公共最终类FontAwareTabLayout扩展表格布局{
私有字符串路径;
公共FontAwareTabLayout(上下文、属性集属性){
超级(上下文,attrs);
fontPath=pullFontPathFromView(上下文,attrs,新int[]{R.attr.fontPath});
}
/**
*尝试直接从TextView中提取自定义属性。
*
*@param context活动上下文
*@param attrs视图属性
*@param attributeId如果-1返回空值。
*@如果未定义属性或未将属性添加到视图中,则返回null
*/
静态字符串pullFontPathFromView(上下文上下文、属性集属性、int[]属性ID){
if(attributeId==null | | attrs==null)返回null;
最后一个字符串attributeName;
试一试{
attributeName=context.getResources().getResourceEntryName(attributeId[0]);
}catch(Resources.notfounde异常){
//无效的属性ID
返回null;
}
final int stringResourceId=attrs.getAttributeResourceValue(null,attributeName,-1);
返回stringResourceId>0?context.getString(stringResourceId)
:attrs.getAttributeValue(null,attributeName);
}
@凌驾
public void addTab(@NonNull Tab,int位置,boolean setSelected){
super.addTab(tab,position,setSelected);
视图组主视图=(视图组)getChildAt(0);
视图组tabView=(视图组)mainView.getChildAt(tab.getPosition());
int tabChildCount=tabView.getChildCount();
对于(int i=0;i
更新:

见(目前) androido允许您通过在res/font/文件夹中添加字体文件来捆绑字体作为资源。这些字体在您的R文件中编译,并在Android Studio中自动提供。您可以使用新的资源类型font访问字体资源。例如,要访问字体资源,请使用@font/myfont或R.font.myfont

要将字体添加为资源,请在Android Studio中执行以下步骤:

  • 右键单击res文件夹并转到New>Android资源目录。此时会出现“新建资源目录”窗口
  • 在资源类型列表中,选择字体,然后单击确定。 注意:资源目录的名称必须是font

  • 在字体文件夹中添加字体文件。 下面的文件夹结构生成R.font.dancing_脚本、R.font.lobster和R.font.typo_图形。 在资源目录中添加字体文件

  • 双击字体文件以在编辑器中预览文件的字体

  • 创建字体系列

    新字体资源文件,类似文件
    
    
    -- 然后我就这么看

     <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lobster"/>
    

    您好,我认为这是使用书法库实现这一目标的简单而最好的方法。

    fontName是“fonts/cocon_next_font.ttf”等资产中的字体名称

    public static void changeTabsFont(TabLayout TabLayout,String fontName){
    ViewGroup vg=(ViewGroup)tabLayout.getChildAt(0);
    int tabscont=vg.getChildCount();
    对于(int j=0;j
    如果使用FragmentPagerAdapter,可以在getPageTitle中使用Spanable,例如:

    override fun getPageTitle(position: Int): CharSequence? {
            val sBuilder = SpannableStringBuilder()
            when(position){
                0->    sBuilder.append("First Tab")
                1->    sBuilder.append("Second Tab")
                else-> sBuilder.append("Third Tab")
            }
            CalligraphyTypefaceSpan(TypefaceUtils.load(getAssets(), "fonts/Roboto-Bold.ttf"))
            return sBuilder
    }
    

    这个解决方案实际上是可行的,并且易于实现和维护。
     <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lobster"/>
    
    public static void changeTabsFont(TabLayout tabLayout, String fontName) {
    
            ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
            int tabsCount = vg.getChildCount();
            for (int j = 0; j < tabsCount; j++) {
                ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
                int tabChildsCount = vgTab.getChildCount();
                for (int i = 0; i < tabChildsCount; i++) {
                    View tabViewChild = vgTab.getChildAt(i);
                    if (tabViewChild instanceof TextView) {
                        CalligraphyUtils.applyFontToTextView(tabLayout.getContext(), (TextView) tabViewChild, fontName);
                    }
                }
            }
        }
    
    override fun getPageTitle(position: Int): CharSequence? {
            val sBuilder = SpannableStringBuilder()
            when(position){
                0->    sBuilder.append("First Tab")
                1->    sBuilder.append("Second Tab")
                else-> sBuilder.append("Third Tab")
            }
            CalligraphyTypefaceSpan(TypefaceUtils.load(getAssets(), "fonts/Roboto-Bold.ttf"))
            return sBuilder
    }