如何在 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:textSize="24sp"
      android:textStyle="bold"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"/>
</RelativeLayout>

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

import androidx.appcompat.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 textView = findViewById(R.id.textView);
      int intColor = -16895234;
      String hexColor = Integer.toHexString(intColor).substring(2);
      textView.setText("#"+hexColor);
   }
}

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

單擊 此處 下載專案程式碼

更新於: 2020 年 7 月 07 日

4K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告