2012-06-06 36 views

回答

9

您可以創建資源文件夾的字體(即資產/字體/ 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" /> 
+1

最好創建一個通用的自定義TextView(例如稱爲TypeFaceTextView),您可以通過預定義屬性app指定自己的字體:fontFamily – MikeL

17

使用自定義字體

第一步是選擇一個您要使用的字體。

第二次在資產目錄中創建一個Fonts文件夾,並在那裏複製你的字體。

enter image description here

注:你可以把你的字體上到處都是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); 
    } 
} 

你可以看到結果:

enter image description here

2

由於的Android 1.5工作室的。1,您可以:

  1. 鼠標右鍵點擊你app目錄
  2. New>Folder(這是靠近列表的底部,很容易錯過)>Assets Folder
  3. 在大多數情況下,你可以離開文件夾的位置作爲默認>點擊Finish
  4. 移動文件到新創建的文件夾assets
相關問題