2011-08-03 78 views
32

在我的应用程序中,我需要对所有textviews和编辑文本字段使用helvetica字体。除了每个textview使用settypeface方法之外,还有什么办法可以做到吗?任何建议将是一个很大的帮助。为完整的android应用程序添加自定义字体

在此先感谢!

+0

访问这一个:可能是它可以对你有所帮助: http://stackoverflow.com/questions/2888508/how-to-change-the-font-on-the-textview/16166184#16166184 – 2013-04-23 11:16:53

+0

不,没有办法。你必须捆绑你的字体,并像尼克说的那样去做。你也可以看看这个线程[http://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android](http://stackoverflow.com/questions/2376250/custom-fonts-and -xml-layouts-android) –

+0

对于任何需要ac#/ Xamarin解决方案的人来说,它扩展了textview,但也使得它是通用的,即你可以通过特定的字体路径作为xml上每个textview的属性,然后在这里查看https: //github.com/Cheesebaron/Cheesebaron.FontSample –

回答

63

我明白了我的意思。这是我使用的代码。我创建了具有自定义字体作为默认字体的自定义TextView

public class MyTextView extends TextView { 

    public MyTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(); 
    } 

    public MyTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public MyTextView(Context context) { 
     super(context); 
     init(); 
    } 

    private void init() { 
     Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf"); 
     setTypeface(tf ,1); 

    } 

} 
+0

你不需要扩展“TextView”,但感谢提示 – mxg

+2

@mxg我没有得到你所说的 – Chrishan

+9

@mxg通过覆盖TextView,他能够在他的布局文件中使用MyTextView,而无需以编程方式执行任何操作活动/片段来实现自定义字体。 –

9

创建一个样式并使用它的所有文本属性。

<style name="CustomText"> 
    <item name="android:typeface">YourFontName</item> 
</style> 

使用它:

<TextView style="@style/CustomText" /> 

以上是使用自定义字体中的所有活动进行定制,你可以使用....

Typeface font = Typeface.createFromAsset(getAssets(), "CustomFontName.ttf"); 
txt.setTypeface(font); 

尝试。

+11

android:typeface字段只允许使用内置的字体名称。我如何分配资产文件夹中的自定义字体名称? – Chrishan

+0

@Chrishi看到我编辑了答案。 – Hanry

+0

+1你的回答帮助我很多@hanry –

0

好吧,你可以做到这一点,但你基本上想做的是一个有点地图格式的字体地图集(它必须以unicode的顺序开始运行!“#$%'()x +, - 。/) 。这个函数做的是取一个字符串,并计算每个对应字母在地图集中的位置。

它不是很容易,但每个字符必须具有相同的长度和宽度,但可以有不同的长度困难得多。

27

在你的活动,你叫

的setContentView之后(RI d.blahblah);

您应该运行一个方法来遍历小部件的整个层次结构并处理字体替换,如:

setContentView(R.id.blahblah); 
Utils.overrideFonts(this, findViewById(android.R.id.content)); 

而提到的“overrideFonts”方法应该是类似的;

public static void overrideFonts(final Context context, final View v) { 
    try { 
     if (v instanceof ViewGroup) { 
      ViewGroup vg = (ViewGroup) v; 
      for (int i = 0; i < vg.getChildCount(); i++) { 
       View child = vg.getChildAt(i); 
       overrideFonts(context, child); 
      } 
     } else if (v instanceof TextView) { 
      ((TextView)v).setTypeface(FONT_REGULAR); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     // ignore 
    } 
} 

在这个方案中,FONT_REGULAR应以安全的地方如果你使用一个子类初始化,您可以看上一单或一些其他的方式,以确保它是正确的初始化...

private static void initializeFonts(final Context context) { 
    FONT_REGULAR = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_medium.otf"); 
    FONT_BOLD = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_bold.otf"); 
} 

活动像MyAppActivity(扩展活动),那么你不需要改变每个和每个活动类的这种自定义。相反,你可以切入它并覆盖这样的行为;

public class MyAppActivity extends Activity { 
... ... 
    @Override 
    public void setContentView(final int layoutResID) { 
     super.setContentView(layoutResID); 
     Utils.overrideFonts(this, findViewById(android.R.id.content)); 
    } 
... ... 
} 

这样你可以使用你的任何活动有共同的行为;

public class SettingsUI extends MyAppActivity { 
... ... 
} 

我希望它有帮助... 干杯!

+6

这是简单布局的一个很好的解决方案。但是,如果您的活动中有ListView,则这不起作用。 ListView中的项目在setContent方法之后实例化,因此,列表中的TextView不会受此方法的影响 – Maggie

+0

您是对的,那些需要在... ItemAdapter类 – lithium

+2

那么操作栏的字体呢? –

0

您可以在http://bit.ly/1bzjWQn

使用PixlUI导入自己的.jar在您的项目。使用它在XML

<com.neopixl.pixlui.components.textview.TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/hello_world" 
    pixlui:typeface="MyFont.ttf" /> 

不要忘实施方案(的xmlns:pixlui = “http://schemas.android.com/apk/com.neopixl.pixlui”)

+1

为什么我们需要添加一些jar来完成我们纯粹用Android本身所做的事情? – Chrishan

+0

您不能在Android SDK中使用自定义字体 – odemolliens

6

要应用自定义字体在所有的应用程序,只需创建以下活动:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    FontManager.getInstance().initialize(this, R.xml.fonts); 
    setContentView(R.layout.main); 
} 
@Override 
public View onCreateView(String name, Context context, AttributeSet attrs) { 
    SimpleFactory factory = new SimpleFactory(); 
    return factory.onCreateView(name, context, attrs); 
} 

其中FontManager这是管理,在/xml/fonts.xml和SimpleFactory只是工厂,创建视图和应用自定义字体每个定义的所有字体类查看实例的文本视图。

/xml/fonts.xml

<?xml version="1.0" encoding="utf-8"?> 
<familyset> 
    <family> 
     <nameset> 
      <!--Font name--> 
      <name>HelveticaNeueLTStd</name> 
     </nameset> 
     <fileset> 
      <!--Font styles--> 
      <file style="normal">fonts/HelveticaNeueLTStd-LtCn.otf</file> 
      <file style="bold">fonts/HelveticaNeueLTStd-MdCn.otf</file> 
      <file style="italic">fonts/HelveticaNeueLTStd-LtCnO.otf</file> 
      <file style="bold_italic">fonts/HelveticaNeueLTStd-MdCnO.otf</file> 
     </fileset> 
    </family> 
    <family> 
     <!--There new font family can be added, 
don't forget add font files into /assets/fonts directory and 
put the name of the font into /values/string/font.xml--> 
    </family> 
</familyset> 

FontFactory - abastract类,只是扩展它来创建自己的工厂

public abstract class FontFactory implements LayoutInflater.Factory{ 
    public final String TAG = getClass().getSimpleName(); 

    static final Class<?>[] mConstructorSignature = new Class[] {Context.class, AttributeSet.class}; 
    final Object[] mConstructorArgs = new Object[2]; 
    private static final String[] sClassPrefixList = { 
      "android.widget.", 
      "android.webkit." 
    }; 

    @Override 
    public View onCreateView(String name, Context context, AttributeSet attrs) { 
     if("ViewStub".equals(name) || "View".equals(name)){ 
      return null; 
     } 
     View view = null; 
     Constructor<? extends View> constructor = null; 
     Class clazz = null; 

     if (view == null) { 
      if (-1 == name.indexOf('.')) { 
       for (String prefix : sClassPrefixList) { 
        clazz = getClazz(prefix, name); 
        if(clazz != null){ 
         break; 
        } 
       } 
      } else { 
       clazz = getClazz("", name); 
      } 
     } 

     if (clazz == null) { 
      Log.d(TAG, "View can't be created " + name); 
      return null; 
     } 

     try { 
      constructor = clazz.getConstructor(mConstructorSignature); 
     } catch (NoSuchMethodException e) { 
      e.printStackTrace(); 
     } 

     Object[] args = mConstructorArgs; 
     args[1] = attrs; 

     if(constructor == null){ 
      return null; 
     } 

     try { 
       view = constructor.newInstance(context, attrs); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
     } 

     if(view != null){ 
      onFontApply(context, view); 
     } 
     return view; 
    } 

    public abstract void onFontApply(Context context, View view); 

    private Class getClazz(String prefix, String name){ 
     Class clazz = null; 
     try { 
      clazz = Class.forName(prefix + name); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } finally { 
      return clazz; 
     } 
    } 
} 

FontManager - 只是映射/ XML /字体定义字体文件。 xml放置在/ assets目录中的字体文件,并通过字体名称和字体样式返回TypeFace。

public void initialize(Context context, int resId) { 
    if(mFonts != null){ 
     Log.d(TAG,"FontManager have already initialized"); 
     return; 
    } 
    XmlResourceParser parser = null; 
    try { 
     parser = context.getResources().getXml(resId); 
     mFonts = new ArrayList<Font>(); 

     String tag; 
     String fontStryleAttr = null; 
     int eventType = parser.getEventType(); 

     Font font = null; 

     do { 
      tag = parser.getName(); 

      switch (eventType) { 
       case XmlPullParser.START_TAG: 
        if (tag.equals(TAG_FAMILY)) { 
         // one of the font-families. 
         font = new Font(); 
        } else if (tag.equals(TAG_NAMESET)) { 
         // a list of font-family names supported. 
         font.families = new ArrayList<String>(); 
        } else if (tag.equals(TAG_NAME)) { 
         isName = true; 
        } else if (tag.equals(TAG_FILESET)) { 
         // a list of files specifying the different styles. 
         font.styles = new ArrayList<FontStyle>(); 
        } else if (tag.equals(TAG_FILE)) { 
         isFile = true; 
         fontStryleAttr = parser.getAttributeValue(null, ATTR_STYLE); 
        } 
        break; 

       case XmlPullParser.END_TAG: 
        if (tag.equals(TAG_FAMILY)) { 
         // add it to the list. 
         if (font != null) { 
          mFonts.add(font); 
          font = null; 
         } 
        } else if (tag.equals(TAG_NAME)) { 
         isName = false; 
        } else if (tag.equals(TAG_FILE)) { 
         isFile = false; 
         fontStryleAttr = null; 
        } 
        break; 

       case XmlPullParser.TEXT: 
        String text = parser.getText(); 
        if (isName) { 
         // value is a name, add it to list of family-names. 
         if (font.families != null) 
          font.families.add(text); 
        } else if (isFile) { 
         // value is a file, add it to the proper kind. 
         FontStyle fontStyle = new FontStyle(); 
         fontStyle.font = Typeface.createFromAsset(context.getAssets(), text); 
         String attr = parser.getAttributeValue(null, ATTR_STYLE); 
         if (fontStryleAttr.equals(STYLE_BOLD)) 
          fontStyle.style = Typeface.BOLD; 
         else if (fontStryleAttr.equals(STYLE_ITALIC)) 
          fontStyle.style = Typeface.ITALIC; 
         else if (fontStryleAttr.equals(STYLE_BOLD_ITALIC)) 
          fontStyle.style = Typeface.BOLD_ITALIC; 
         else 
          fontStyle.style = Typeface.NORMAL; 
         font.styles.add(fontStyle); 
        } 
      } 

      eventType = parser.next(); 

     } while (eventType != XmlPullParser.END_DOCUMENT); 

    } catch (XmlPullParserException e) { 
     throw new InflateException("Error inflating font XML", e); 
    } catch (IOException e) { 
     throw new InflateException("Error inflating font XML", e); 
    } finally { 
     if (parser != null) 
      parser.close(); 
    } 
} 

public Typeface get(String family, int style) { 
    for (Font font: mFonts) { 
     for (String familyName : font.families) { 
      if (familyName.equals(family)) { 
       // if no style in specified, return normal style. 
       if (style == -1) 
        style = Typeface.NORMAL; 
       for (FontStyle fontStyle : font.styles) { 
        if (fontStyle.style == style) 
         return fontStyle.font; 
       } 
      } 
     } 
    } 
    return mDefaultFont; 
} 

更多的代码和样品只看here

0
setContentView(R.layout.activity_main); 
    custfont(this, findViewById(android.R.id.content)); 



private void custfont(final Context context, View v) 
{ 
    try 
    { 
     if (v instanceof ViewGroup) 
     { 
      ViewGroup vg = (ViewGroup) v; 

      for (int i = 0; i < vg.getChildCount(); i++) 
      { 
       View child = vg.getChildAt(i); 
       overrideFonts(context, child); 
      } 
     } 
     else if (v instanceof TextView) 
     { 
      ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ostrichblack.ttf")); 
     } 
    } 
    catch (Exception e) 
    { 
    } 
} 
0
import android.content.Context; 
import android.graphics.Typeface; 

/** 
* Created by Sanjeev Kumar on 4/18/2017. 
*/ 

public class FontManager { 
    public Context mContext; 

    public FontManager(Context context) { 
     this.mContext = context; 
    } 

    public Typeface getSquarkiFont() { 
     return Typeface.createFromAsset(mContext.getAssets(), "fonts/Squarki.ttf"); 
    } 

    public Typeface getLazySpringDayFont() { 
     return Typeface.createFromAsset(mContext.getAssets(), "fonts/LazySpringDay.ttf"); 
    } 
} 
相关问题