如何支持Android默认语言环境中不存在的自定义语言环境字体

时间:2016-09-22 07:05:28

标签: android fonts locale custom-font

我正在尝试构建一个用于本地化语言本地化的简单应用程序

  

" Meitei mayek"印度曼尼普尔

不在Android区域设置列表中。

我有 .ttf 文件。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

  1. 在资源下创建字体目录,并将.ttf文件放入字体中。

    assets/fonts
    
  2. 只要您想设置,请使用以下代码。

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);
    

答案 1 :(得分:0)

您可以创建自定义TextView 以支持显示文字的自定义字体。试试:

1-将.ttf字体文件放在项目的assets文件夹中。

2-创建一个扩展TextView的类

public class TextViewIndian extends AppCompatTextView {

public TextViewIndian(Context context) {
    super(context);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}

public TextViewIndian(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}
public TextViewIndian(Context context, AttributeSet attrs) {
    super(context, attrs);
    setTypeface(FontFactory.getInstance(context).getMyFont());
}

}

如上所示,您需要在FontFactoryload the font files from assets中将另一个名为singleton way的班级改为avoid memory leaks

public class FontFactory {

private static Typeface MYFONT;

private static FontFactory instance ;

private FontFactory(Context context){
    MYFONT = Typeface.createFromAsset(context.getAssets(),"font.ttf");
}

public static FontFactory getInstance(Context context){
    if(instance == null)
        instance = new FontFactory(context);
    return instance ;
}

public Typeface getMyFont(){

    return MYFONT;
}

}

您可以将same approach用于Button and EditText等其他小部件,为您的语言创建自定义小部件。

现在,您可以将此TextViewIndian放置在layout.xml文件中,并以您使用任何其他窗口小部件的方式使用它们,并自动为其文本设置自定义字体。