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

Cách đặt màu nền (background color) cho View trong Android?

Giới thiệu

Bài viết minh họa cách thiết lập màu nền cho View (TextView, Button, Layout...) trong Android qua XML và code Java.

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

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

Khởi tạo project Android Studio.

Bước 2: Giao diện TextView có màu nề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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:background="#046B5F"
        android:padding="16dp"
        android:text="Màu nền View của tôi"
        android:textColor="#FFFFFF" />
</RelativeLayout>

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

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Bước 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. TextView hiển thị với nền màu xanh đậm (#046B5F) và chữ trắng.

Cách đặt màu nền (background color) cho View trong Android?

Các cách đặt màu nền

1. Trong XML (khuyên dùng cho static UI)

<!-- Mã hex ARGB/RGB -->
android:background="#FF0000"        <!-- Đỏ -->
android:background="#80FF0000"      <!-- Đỏ 50% trong suốt -->
android:background="@color/colorPrimary" <!-- Từ res/values/colors.xml -->
android:background="@drawable/my_shape" <!-- Drawable shape/gradient -->

2. Trong Java/Kotlin (dynamic runtime)

// Color int (ARGB)
view.setBackgroundColor(Color.parseColor("#046B5F"));
view.setBackgroundColor(Color.RED);
view.setBackgroundColor(0xFF046B5F); // ARGB

// Từ resource
view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
view.setBackgroundResource(R.drawable.my_shape);
view.setBackground(ContextCompat.getDrawable(context, R.drawable.my_shape));

3. Drawable Shape (XML res/drawable/)

<!-- res/drawable/rounded_bg.xml -->
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary" />
    <corners android:radius="8dp" />
    <stroke android:width="2dp" android:color="@color/colorAccent" />
</shape>

Lưu ý quan trọng

  • setBackgroundColor() nhận Color Int (ARGB), không phải Resource ID
  • Dùng ContextCompat.getColor() để tương thích mọi API level
  • setBackgroundResource() / setBackground() nhận Resource ID (@drawable/...)
  • Background color che phủ background drawable trước đó
  • Để trong suốt: Color.TRANSPARENT hoặc #00000000

Màu trong Material Design

Sử dụng colorPrimary, colorPrimaryVariant, colorSecondary, colorSurface, colorBackground, colorError từ theme MaterialComponents để đảm bảo nhất quán và hỗ trợ Dark Mode tự động.