如何在Android应用程序中使用自定义字体

时间:2014-04-05 08:10:45

标签: android

为了实现自定义字体,我看到这里的几个例子问题不同,我在一个抽象类中使用自定义字体,这是在整个应用程序中使用,这是我的代码

 public abstract class X extends Activity implements OnClickListener {

    private Vibrator vibrator;
    private TextView TV_score;
    private TextView TV_hints;
    private ImageButton BTN_back;
        // Font path
    private String fontPath = "fonts/CarterOne.ttf";
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    public static Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.log("onCreate " + this.getClass().getName());
        vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        context = getBaseContext();
        SoundHandler.getInstance().initSounds(context);         
    }

通过调试尝试这里我得到空指针异常

Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);

如何解决这个问题给出了一些建议。

4 个答案:

答案 0 :(得分:1)

在onCreate活动方法中创建字体对象

public abstract class X extends Activity implements OnClickListener {

private Vibrator vibrator;
private TextView TV_score;
private TextView TV_hints;
private ImageButton BTN_back;
    // Font path
private String fontPath = "fonts/CarterOne.ttf";
Typeface tf ;
public static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Logger.log("onCreate " + this.getClass().getName());
    vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
    context = getBaseContext();
    SoundHandler.getInstance().initSounds(context);   
    tf = Typeface.createFromAsset(getAssets(), fontPath);      
}

答案 1 :(得分:1)

tf中分配onCreate()的值然后解决您的问题。

答案 2 :(得分:1)

您可以使用图书馆; Calligraphy

答案 3 :(得分:0)

In android , you can define your own custom fonts for the strings in your application. You just need to download the required font from the internet, and then place it in assets/fonts folder.

After putting fonts in the assets folder under fonts folder, you can access it in your java code through Typeface class. First , get the reference of the text view in the code. Its syntax is given below:

TextView tx = (TextView)findViewById(R.id.textview1);
The next thing you need to do is to call static method of Typeface class createFromAsset() to get your custom font from assets. Its syntax is given below:

Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font name.ttf");
The last thing you need to do is to set this custom font object to your TextView Typeface property. You need to call setTypeface() method to do that. Its syntax is given below:

tx.setTypeface(custom_font);