ภาพรวม
ตัวอย่างนี้สาธิตการแปลงค่าสีแบบ Integer (ARGB) ให้เป็น Hex String (#RRGGBB) ใน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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:textSize="24sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (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; // ตัวอย่างค่าสี Integer
String hexColor = Integer.toHexString(intColor).substring(2); // ตัด Alpha ออก (2 ตัวแรก)
textView.setText("#" + hexColor);
}
}
คำอธิบาย
Integer.toHexString(intColor)แปลง Integer เป็น Hex String (8 ตัวอักษร รวม Alpha).substring(2)ตัด 2 ตัวแรก (Alpha channel) ออก เพื่อให้เหลือ RRGGBB 6 ตัว- ต่อ
#นำหน้า เพื่อให้เป็นรูปแบบสีมาตรฐาน
ตัวอย่างค่าสีทั่วไป
| สี | Integer (ARGB) | Hex (#RRGGBB) |
|---|---|---|
| แดง | -65536 | #FF0000 |
| เขียว | -16711936 | #00FF00 |
| น้ำเงิน | -16777216 | #0000FF |
| ขาว | -1 | #FFFFFF |
| ดำ | -16777216 | #000000 |
ขั้นตอนที่ 4: 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>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
การทดสอบ
รันแอป จะแสดงค่า Hex ของสีตัวอย่าง
