【问题标题】:how to create custom font in android?如何在android中创建自定义字体?
【发布时间】:2014-09-07 16:13:58
【问题描述】:

如何使用我们在 xml 中的资产文件夹中添加的自定义字体? 我想为应用程序创建自定义字体.. 但我运行程序,它有异常。 这是我的java代码:

  public class MainActivity extends TextView {

  private static final String TAG = "TextView";

    public MainActivity(Context context) {
        super(context);
    }

    public MainActivity(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public MainActivity(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.textfont);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        }

        setTypeface(tf);  
        return true;
    }


}

并在 res/values/attrs 中创建一个文件夹

 <?xml version="1.0" encoding="utf-8"?>
   <resources>
   <declare-styleable name="textfont">
    <attr name="customFont" format="string"/>
</declare-styleable>
 </resources>

和xml:

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.example.changfont"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<com.example.changfont.MainActivity
    android:id="@+id/textViewPlus1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:text="helooo"
    foo:customFont="aaa.ttf">
</com.example.changfont.MainActivity>

logcat 是:

 09-09 20:44:28.063: E/AndroidRuntime(11515): FATAL EXCEPTION: main
 09-09 20:44:28.063: E/AndroidRuntime(11515): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.changfont/com.example.changfont.MainActivity}: java.lang.InstantiationException: can't instantiate class com.example.changfont.MainActivity; no empty constructor
 09-09 20:44:28.063: E/AndroidRuntime(11515):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)

不知道是什么问题? 请帮帮我。

【问题讨论】:

标签: android


【解决方案1】:

您的MainActivity 不是Activity,而是TextView。它不能被实例化为一个活动,也不应该在清单中声明。

看来您需要:

  • 将此 MainActivity 重命名为 `MyCustomTextView``

  • MainActivity 实现为一个调用setContentView() 的活动,其布局包含您的MyCustomTextView 实例,例如您发布的XML(MainActivity 重命名)。

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2021-11-04
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多