如何在 Android 中更改 TextView 的字型顏色?


本示例演示如何在 Android 中更改 TextView 的字型顏色。

步驟 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/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="My color is Blue"
      android:layout_centerInParent="true"
      android:textStyle="bold"
      android:textSize="36sp"/>
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/textView1"
      android:layout_marginBottom="10dp"
      android:text="My color is Green"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:textSize="36sp" />
</RelativeLayout>

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

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
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 textView1 = findViewById(R.id.textView1);
      textView1.setTextColor(Color.BLUE);
      TextView textView2 = findViewById(R.id.textView2);
      textView2.setTextColor(Color.parseColor("#006400"));
   }
}

步驟 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 Studio 中執行應用程式,請開啟其中一個專案活動檔案,然後單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕

點選 這裡 下載專案程式碼。

更新日期: 2019 年 8 月 2 日

5K+ 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

立即開始
廣告