如何使用我的xml资产文件夹中添加的自定义字体?我知道我们可以在java中使用setTypeface()
方法,但我们必须在使用TextView
的任何地方执行此操作。那么有更好的方法吗?
答案 0 :(得分:57)
我通过Google搜索找到的最佳方式是 - 如果你想在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之前版本的内存泄漏。
答案 1 :(得分:2)
将您的字体文件放在asset\fonts\fontname
在xml文件中定义三个textview,然后将此代码放在您的活动类中:
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);
}
}