如何在Android中为toast设置hindi自定义字体?

时间:2013-01-31 06:47:14

标签: android localization typeface

我正在用多种语言创建一个短信应用程序。对于印地语,我在资产/字体文件夹中包含了DroidHindi.ttf文件。我可以使用以下方法在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消息时实现它。

Toast.makeText(getBaseContext(), R.string.toast_msg ,Toast.LENGTH_SHORT).show();

除此代码外,我还需要实现DroidHindi.ttf文件。

我有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:1)

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();

答案 1 :(得分:0)

首先添加此类

ADD

然后只需使用此方法

SUB

致电:

  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);
    }

}

to toast:

    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"));

别忘了在onCreate:

中添加此代码
    public void spannableToast(SpannableString text) {
    Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}