Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Fonts Android如何在课堂上打字_Fonts_Font Face - Fatal编程技术网

Fonts Android如何在课堂上打字

Fonts Android如何在课堂上打字,fonts,font-face,Fonts,Font Face,我有两个类,第一个叫做Font.java,它有以下代码 package com.example.font; package com.example.font; import android.content.Context; import android.graphics.Typeface; public final class Font { static Context context; // Font path

我有两个类,第一个叫做Font.java,它有以下代码

   package com.example.font;

    package com.example.font;

    import android.content.Context;
    import android.graphics.Typeface;

    public final class Font {
        static Context context;

        // Font path
        static  String fontPath = "fonts/font.ttf";
        // Loading Font Face
        static Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
    }
第二节课是一项活动,它有以下内容

        package com.example.font;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    public class AndroidExternalFontsActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // text view label
            TextView txtGhost = (TextView) findViewById(R.id.ghost);


            // Applying font
            txtGhost.setTypeface(Font.tf);
        }
    }
我想将font.java类中的字体设置为Activity类中的TextView

我试过上面的代码,但不起作用 我该怎么做


谢谢。

你的字体类错了。您的上下文变量从未赋值,因此

context.getAssets()
您将有一个NullPointerException

也请考虑<强>绝对值> />强,在上下文中使用静态引用,因为它是一个记录良好的内存泄漏源,如您可以检查,例如

我建议您将字体类修改为类似于:

package com.example.font;

    package com.example.font;

    import android.content.Context;
    import android.graphics.Typeface;

    public final class Font {
        private static final String fontPath = "fonts/font.ttf";

        public Typeface getFont(Context context) {
            return Typeface.createFromAsset(context.getAssets(), fontPath);

        }
    }
您的活动将如下所示:

public class AndroidExternalFontsActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // text view label
        TextView txtGhost = (TextView) findViewById(R.id.ghost);


        // Applying font
        txtGhost.setTypeface(Font.getFont(this));
    }
}

此外,答案可能对您有所帮助。

thx了解答案,但之后如何在活动中设置字体?