如何在原生Android应用中使用Font Awesome?


此示例演示了如何在原生Android应用程序中使用FontAwesome。

步骤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:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:text="FontAwesome"
   android:textSize="48sp"
   android:textStyle="bold" />
</RelativeLayout>

步骤3 - 创建一个新的下载资产文件夹。将fontAwesome.ttf复制粘贴到资产文件夹中。

步骤4 - 将以下代码添加到src/MainActivity.java

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.textView);
      Typeface font = Typeface.createFromAsset(getAssets(), "FontAwesome.ttf");
      textView.setTypeface(font);
   }
}

步骤5 - 将以下代码添加到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 Studio运行应用程序,请打开您的项目之一的活动文件,然后单击工具栏中的运行播放图标 图标。选择您的手机设备作为选项,然后检查您的手机设备,它将显示您的默认屏幕 -

更新于: 2020年7月7日

435 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告