2012-09-23 215 views
2

如何更改Android TextView中的字體類型?更改TextView字體?

<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Welcome!" 
    android:textSize="20sp" /> 

回答

6

您可以使用android:typeface屬性。例如:

<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Welcome!" 
    android:typeface="sans" 
    android:textSize="20sp" /> 

的XML屬性只允許值normalsansserif,和monospace。如果您想使用其他Typeface(可能是您的應用程序附帶的自定義版本),則必須在加載TextView後通過調用來查看代碼。

+0

現在什麼是一些不同類型的面孔? – apw2012

+0

@ apw2012 - 通常只能依賴系統中存在的一組類型面 - 通過允許的XML值訪問的面。它曾經是「Droid Sans」,「Droid Sans Mono」和「Droid Serif」。從冰淇淋三明治(4.0)開始,它就是「Roboto」系列(在這裏描述)(http://developer.android.com/design/style/typography.html)。對於其他任何東西,您都需要將它與應用一起發貨,並使用'TypeFace.createFrom ...'方法之一加載它(例如@Siddharth描述)。 –

6

從那裏您引用TextView添加到泰德·霍普的回答,如果你正在尋找一個自定義字體爲您TextView,在你Activity,使用此代碼示例:

Typeface blockFonts = Typeface.createFromAsset(getAssets(),"ROBOTO-MEDIUM_0.TTF"); 
TextView txtSampleTxt = (TextView) findViewById(R.id.your_textview_id); 
txtSampleTxt.setTypeface(blockFonts); 

雖然前你可以使用這個,你需要在assets文件夾中複製你選擇的字體。

你也可以看看我的answer之一,它有幾個網站可以用來下載字體。它們是:

http://www.google.com/webfonts

http://www.fontsquirrel.com/

+1

爲了澄清,如果您想使用以「fonts /」開頭的路徑作爲資產名稱,您只需創建一個'fonts'子文件夾即可。字體也可以從根資產文件夾加載。 –

+0

字樣 \t \t blockFonts = \t \t Typeface.createFromAsset(getAssets(), 「字體/ Lobster.TTF」); \t \t TextView txtSampleTxt =(TextView) \t \t findViewById(R.id.welcome); \t \t txtSampleTxt.setTypeface(blockFonts); – apw2012

+0

好的,所以打開時就會崩潰。我將代碼提供並將其更改爲java – apw2012

0

您可以通過編程方式將您的字體文件(example.tff)風格 資產/字體設置的願望字體,然後給自己的字符串轉換成字體路徑變量

String fontPath="fonts/Unkempt-Regular.ttf"; 
    TextView aboutus=(TextView)findViewById(R.id.aboutus); 
    Typeface type=Typeface.createFromAsset(getAssets(), fontPath); 
    aboutus.setTypeface(type);