2012-09-23 219 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);