如何在 Android 專案中使用自定義字型?


本示例演示瞭如何在 Android 專案中使用自定義字型。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案,填寫所有必需的詳細資訊,建立一個新專案。

步驟 2 − 新增下面的程式碼到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Lets put a smile on your Face!"
      android:textSize="50dp"
      android:layout_centerVertical="true"
      android:layout_marginLeft="5dp" />
</RelativeLayout>

步驟 3 − 新增下面的程式碼到 src/MainActivity.java

import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView tv;
   Typeface myFont;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      tv = (TextView) findViewById(R.id.textView);
      myFont = Typeface.createFromAsset(this.getAssets(), "font/AlexBrush-Regular.ttf");
      tv.setTypeface(myFont);
   }
}

步驟 4 − 新增下面的程式碼到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

嘗試執行你的應用程式。我假設你已經將你的 Android 移動裝置連線到電腦。要從 Android 工作室執行應用程式,請開啟專案的一個活動檔案,並單擊工具欄上的執行  圖示。選擇你的移動裝置作為選項,然後檢視你的移動裝置,它會顯示你的預設螢幕 −

單擊此處下載專案程式碼。

更新時間:2019-08-02

134 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始使用
廣告
© . All rights reserved.