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

Cách đặt màu nền Activity thành vàng lập trình trong Android

Hướng dẫn đơn giản này trình bày cách thay đổi màu nền của Activity (cụ thể là ViewGroup gốc trong layout) bằng code Java/Kotlin trong Android.

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

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Layout (res/layout/activity_main.xml)

Quan trọng: ViewGroup gốc (RelativeLayout) phải có android:id để tham chiếu từ code.

<?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"
    android:id="@+id/relativeLayout"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textStyle="bold"
        android:textSize="24sp"
        android:text="Màu nền Activity là Vàng" />

</RelativeLayout>

Bước 3: Code MainActivity (src/MainActivity.java)

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        relativeLayout = findViewById(R.id.relativeLayout);

        // Đặt màu nền thành vàng
        relativeLayout.setBackgroundColor(Color.YELLOW);

        // Hoặc dùng mã màu hex:
        // relativeLayout.setBackgroundColor(Color.parseColor("#FFFF00"));
        // relativeLayout.setBackgroundColor(0xFFFF00); // ARGB int
    }
}

Bước 4: Cấu hình 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Toàn bộ nền Activity sẽ có màu vàng.

Cách đặt màu nền Activity thành vàng lập trình trong Android

Các cách chỉ định màu trong Android

1. Color constants (Color class)

Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW, Color.BLACK, Color.WHITE,
Color.GRAY, Color.LTGRAY, Color.DKGRAY, Color.CYAN, Color.MAGENTA,
Color.TRANSPARENT

2. Parse từ String hex

Color.parseColor("#FFFF00")        // RGB
Color.parseColor("#FFFFFF00")      // ARGB (8 chữ số)
Color.parseColor("#FFF")           // Shorthand RGB
Color.parseColor("#FFFF")          // Shorthand ARGB

3. ARGB int trực tiếp

// 0xAARRGGBB
int yellow = 0xFFFF00;      // Opacity FF (255), Red FF, Green FF, Blue 00
int semiTransparentRed = 0x80FF0000; // 50% opacity

4. Từ resource (colors.xml)

<!-- res/values/colors.xml -->
<resources>
    <color name="my_yellow">#FFFF00</color>
</resources>

// Java:
ContextCompat.getColor(context, R.color.my_yellow) // API 23+
// Hoặc deprecated:
getResources().getColor(R.color.my_yellow)

5. ColorStateList (màu thay đổi theo state)

<!-- res/color/button_bg.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:color="#FFFF00" android:state_pressed="true" />
    <item android:color="#FFEB3B" android:state_enabled="true" />
    <item android:color="#9E9E9E" /> <!-- default -->
</selector>

// Áp dụng:
view.setBackgroundResource(R.color.button_bg);

Lưu ý quan trọng

  • setBackgroundColor() nhận int là mã màu ARGB, không phải resource ID
  • Để set background từ drawable resource: dùng setBackgroundResource(R.drawable.xxx) hoặc setBackground(ContextCompat.getDrawable(...))
  • Nếu dùng Theme/MaterialComponents, màu nền có thể bị ghi đè bởi android:windowBackground trong theme. Kiểm tra styles.xml
  • Với ConstraintLayout, CoordinatorLayout, FrameLayout... cách làm tương tự: findViewById → setBackgroundColor()