[英]Where should I place font file in Android resources?
我應該在res文件夾中放置我的字體文件(TTF)?
使用自定義字體
第一步是選擇要使用的字體。
其次,在資源目錄中創建一個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>
加載和設置自定義字體的代碼也很簡單,如下所示。
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);
}
}
你可以看到結果:
您可以在資產文件夾中創建字體(即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"));
}
}
}
最后,更新你的布局:
//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" />
不在res文件夾中,而是在assets文件夾中的任何位置。 然后,您可以使用Typeface
的createFromAsset
靜態方法:
您可以在resources
創建fonts
文件夾,並直接在xml中使用它,因為Android O.
查看新的Android O - 字體功能 。
從Android Studio 1.5.1開始,您可以:
app
目錄 New
> Folder
(這位於列表底部附近,很容易錯過)> Assets Folder
assets
文件夾中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.