Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách chuyển đổi màu Integer sang Hex String trong Android

Giới thiệu

Ví dụ này minh họa cách chuyển đổi giá trị màu dạng int (32-bit ARGB) sang chuỗi hexadecimal (ví dụ: #FF0000) bằng phương thức Integer.toHexString().

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Code MainActivity (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);

        // Màu int (ARGB) - ví dụ: đỏ đậm
        int intColor = -16895234; // Tương đương 0xFF0033CC (Blue) hoặc tính từ Color.rgb()

        // Chuyển sang Hex String
        // Integer.toHexString trả về chuỗi không dấu, 8 ký tự cho ARGB (ví dụ: "ff0033cc")
        // substring(2) bỏ qua 2 ký tự đầu (alpha "ff") -> chỉ lấy RGB "0033cc"
        String hexColor = Integer.toHexString(intColor).substring(2);

        // Hiển thị với tiền tố #
        textView.setText("#" + hexColor.toUpperCase()); // #0033CC
    }
}

Bước 4: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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>
                

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. TextView hiển thị mã hex của màu int.

Cách chuyển đổi màu Integer sang Hex String trong Android

Giải thích chi tiết

Cấu trúc int Color (32-bit ARGB)

Bit:  31-24   23-16   15-8    7-0
      Alpha   Red     Green   Blue
      (AA)    (RR)    (GG)    (BB)
  • Giá trị int có dấu (signed 32-bit). Màu không trong suốt (alpha=255) thường là số âm (bit sign = 1).
  • Ví dụ: Color.RED = 0xFFFF0000 = -65536.

Phương pháp chuyển đổi

// Cách 1: Integer.toHexString (cơ bản)
String hex = Integer.toHexString(colorInt); // "ffff0000"
String rgbHex = "#" + hex.substring(2).toUpperCase(); // "#FF0000" (bỏ alpha)

// Cách 2: String.format (đầy đủ ARGB 8 ký tự)
String argbHex = String.format("#%08X", colorInt); // "#FF000000" (có alpha)

// Cách 3: Chỉ RGB (bỏ alpha) - phổ biến cho CSS/Web
String rgbHex = String.format("#%06X", (0xFFFFFF & colorInt)); // "#FF0000"

Các phương thức tiện ích của lớp Color

// Tạo màu từ RGB
int color = Color.rgb(255, 0, 0); // 0xFFFF0000
int color = Color.argb(255, 255, 0, 0); // 0xFFFF0000

// Trích xuất thành phần
int red = Color.red(colorInt);
int green = Color.green(colorInt);
int blue = Color.blue(colorInt);
int alpha = Color.alpha(colorInt);

// Parse từ String hex
int color = Color.parseColor("#FF0000"); // Hỗ trợ #RGB, #ARGB, #RRGGBB, #AARRGGBB

Best Practice

Sử dụng Color.parseColor() và String.format() thay vì thao tác bit thủ công để code an toàn, đọc hiểu dễ dàng.