我正在创建一个多种语言的短信应用程序。对于印地语,我已经将DroidHindi.ttf文件包含在资产/字体文件夹中。 我能够使用它在文本视图和按钮中实现这一点:-
Typeface face;
face = Typeface.createFromAsset(this.getAssets(), "fonts/DroidHindi.ttf");
TextView font1 = (TextView) findViewById(R.id.tv1font);
font1.setTypeface(face, Typeface.BOLD);
TextView font2 = (TextView) findViewById(R.id.tv2font);
font2.setTypeface(face, Typeface.BOLD);
Button bfont = (Button) findViewById(R.id.btnsend);
bfont.setTypeface(face, Typeface.BOLD);
而且它工作得很好。
但是,我无法在显示 Toast 消息时实现它。
Toast.makeText(getBaseContext(), R.string.toast_msg ,Toast.LENGTH_SHORT).show();
除了这段代码,我还需要实现 DroidHindi.ttf 文件。
有什么办法可以做到吗?
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text .setTypeface(face, Typeface.BOLD); // set your typeface here just like you have done above
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
首先添加这个类
public class typeFace extends TypefaceSpan {
Typeface typeface;
public typeFace(String family, Typeface typeface) {
super(family);
this.typeface = typeface;
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setTypeface(typeface);
}
@Override
public void updateMeasureState(TextPaint ds) {
ds.setTypeface(typeface);
}
}
然后简单地使用此方法
public SpannableString spannableString(String string, String font) {
SpannableString span = new SpannableString(string);
span.setSpan(new typeFace("", Typeface.createFromAsset(context.getAssets(),
"fonts/" + font + ".ttf")), 0, span.length(), span.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
叫:
textView.settext(spannableString("your text","DroidHindi"));
吐司 :
public void spannableToast(SpannableString text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
叫:
spannableToast(spannableString("your text","DroidHindi"));
不要忘记在 onCreate 中添加此代码:
Context context=getApplicationContext();