我该如何在xml中使用添加到asset文件夹中的自定义字体?我知道我们可以在java中使用setTypeface()
方法,但这样做需要在每个使用该TextView
的地方都设置一次。那么有更好的方法吗?
我该如何在xml中使用添加到asset文件夹中的自定义字体?我知道我们可以在java中使用setTypeface()
方法,但这样做需要在每个使用该TextView
的地方都设置一次。那么有更好的方法吗?
通过谷歌搜索,我发现最好的方法是- 假设你想在TextView中使用字体,那么我们需要扩展TextView并在其中设置字体,然后我们可以在xml中使用我们自定义的TextView。 下面我将展示扩展的TextView
package com.vins.test;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"your_font.ttf");
setTypeface(tf);
}
}
我们在每个构造函数中调用init()来设置字体。 稍后,我们必须像下面展示的那样在main.xml中使用它。
<com.vins.test.MyTextView
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1"
android:text="This is a text view with the font u had set in MyTextView class "
android:textSize="30dip"
android:textColor="#ff0000"
>
更新:
请注意,根据 pandre 的提醒,早于4.0版本的 Android 存在内存泄漏问题。
asset\fonts\fontname
中。public class AndroidExternalFontsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Font path
String fontPath = "fonts/DS-DIGIT.TTF";
String fontPath1 = "fonts/Face Your Fears.ttf";
String fontPath2 = "fonts/HelveticaNeue-Bold_0.otf";
// text view label
TextView txtGhost = (TextView) findViewById(R.id.ghost);
TextView txtGhost1 = (TextView) findViewById(R.id.ghost1);
TextView txtGhost2 = (TextView) findViewById(R.id.ghost2);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontPath1);
Typeface tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
// Applying font
txtGhost.setTypeface(tf);
txtGhost1.setTypeface(tf1);
txtGhost2.setTypeface(tf2);
}
}