如何设置整个应用程序的字体?

时间:2018-09-15 13:59:29

标签: android fonts

我有1种字体,我想知道:如何为整个应用设置字体? 我的字体在资产文件夹中。 我不希望这些项目一一设置。

此代码是单个设置的字体:

Typeface type=Typeface.createFromAsset(getAssets(),”fonts/Nastaliq.ttf”);
text.setTypeface(type);

但是我想为我的应用程序中的所有文本设置它。

1 个答案:

答案 0 :(得分:1)

您应该为每个对象创建一个CustomView类(例如:CustomTextView),然后在该类中设置字体。 在XML文件中,您必须调用已创建的CustomTextView类(而不是TextView)。然后,所有内容都与TextView相同,并且不需要为每个对象设置字体。这是给你的例子。

Java类:

arr.splice(indexofline,1);

XML文件:

public class CustomTextView extends AppCompatTextView {
private Context context;
public Boolean setBold = false;
public MyTextView(Context context) {
super(context);
this.context = context;
setTF();
}

public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
TypedArray attrsArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyTextView);
setBold = attrsArray.getBoolean(R.styleable.MyTextView_isBold, false);  
setTF();

}
public void setTF() {
String typeAddress = "ir_sans.ttf";
if (setBold)
typeAddress = "ir_sans_bold.ttf";
Typeface sans = Typeface.createFromAsset(context.getAssets(), typeAddress);
this.setTypeface(sans);
    }
}

下次,如果要更改字体,只需替换字体文件并在CustomView中编辑它的名称