[英]How to set hindi custom font for toasts in Android?
我正在創建多種語言的短信應用。 對於印地語,我將DroidHindi.ttf文件包含在assets / fonts文件夾中。 我可以使用以下方法在textview和button中實現此功能:
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.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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.