K_A*_*nas 17
使用自定义字体
第一步是选择要使用的字体.
其次,在资源目录中创建一个Fonts文件夹,然后在那里复制字体.

注意:你可以把你的字体放在asssets文件夹的各处,但这就是我的方式!!
这就是设置,现在是代码.
要访问自定义字体,您必须使用Android SDK中的Typeface类创建Android可以使用的字体,然后设置需要适当使用自定义字体的任何显示元素.为了演示,您可以在主屏幕上创建两个文本视图,一个使用默认的Android Sans字体,另一个使用您的自定义字体.布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/DefaultFontText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="Here is some text." />
<TextView
android:id="@+id/CustomFontText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="Here is some text.">
</TextView>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
加载和设置自定义字体的代码也很简单,如下所示.
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以看到结果:

Mun*_*oor 10
您可以在资产文件夹中创建字体(即asset/fonts/roboto.ttf).
然后,为TextView创建一个合适的类:
// RobotoFont class
package com.my.font;
public class RobotoFont extends TextView {
public RobotoFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public RobotoFont(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RobotoFont(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf"));
}
else if(style == Typeface.ITALIC)
{
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Italic.ttf"));
}
else
{
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,更新你的布局:
//main.xml
//replace textview with package name com.my.font.RobotoFont
<com.my.font.RobotoFont
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
Run Code Online (Sandbox Code Playgroud)
不在res文件夹中,而是在assets文件夹中的任何位置.然后你可以使用createFromAsset静态方法Typeface:
| 归档时间: |
|
| 查看次数: |
23148 次 |
| 最近记录: |