我如何设置字体,其ttf位于我的assets
文件夹中通过xml? 我知道how to do that programmatically,但你怎么能通过XML来做到这一点?提前致谢。通过xml设置自定义字体
1
A
回答
14
您无法直接使用XML,但可以扩展TextView
并设置默认字体。
package com.nannu;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class NanTV extends TextView{
private Context c;
public NanTV(Context c) {
super(c);
this.c = c;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
}
public NanTV(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.c = context;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
// TODO Auto-generated constructor stub
}
public NanTV(Context context, AttributeSet attrs) {
super(context, attrs);
this.c = context;
Typeface tfs = Typeface.createFromAsset(c.getAssets(),
"font/yourfont.ttf");
setTypeface(tfs);
}
}
而在你的布局中使用新TextView
<com.nannu.NanTV
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
我从我的上一个答案张贴这https://stackoverflow.com/a/11239305/1166537
3
如果您创建了自己的TextView
派生项,您可以添加该类处理编程方式的XML属性。这样,你指定一个特定的字体,它会被设置为运行时,但你通过XML来做到这一点。 :)
否则,没有已知的方法来实现所请求的行为。
1
您可以通过编写自定义的TextView做到这一点,否则你将不得不设置它以编程方式。欲了解更多详细信息,请参阅本link
1
我创建了一个库来解决这个问题就在这里:http://responsiveandroid.com/2012/03/15/custom-fonts-in-android-widgets.html
你伸出一个TextView,并设置在XML字体的名称。有一个可下载的样本。
0
,你可以在你的XML,如指定字体
<com.github.browep.customfonts.view.FontableTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is in a custom font"
app:font="MyFont-Bold.otf" />
代码支持FontableTextView和FontableButton,但它很容易扩展到支持其他窗口小部件类型,如果你需要。
听起来不错,你能举个例子吗?我认为很多人都没有想过这样做。 – 2012-07-13 13:46:33
如果你在下面检查iNan的例子,它会是这样(只需添加自定义属性并通过“AttributeSet attrs”获取它们)。我的日食已经坏了,所以我现在无法完全帮助你解决实际的问题。 :( – ninetwozero 2012-07-13 13:53:20