我如何設置字體,其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