Giới thiệu
Hướng dẫn này trình bày cách thay đổi màu chữ và màu nền của CheckBox trong Android theo chương trình.
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: Thiết kế 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:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhấn vào checkbox" />
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check box"
android:layout_below="@id/tv"
android:paddingRight="15dp"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Đổi màu"
android:layout_below="@id/checkbox" />
</RelativeLayout>
Bước 3: Viết logic xử lý (src/MainActivity.java)
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CheckBox checkBox = findViewById(R.id.checkbox);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
// Đổi màu chữ thành đỏ
checkBox.setTextColor(Color.RED);
// Đổi màu nền thành xanh lá nhạt
checkBox.setBackgroundColor(Color.parseColor("#cbff75"));
});
}
}
Bước 4: Cấu hình 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>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Lưu ý nâng cao
setTextColor()chỉ thay đổi màu chữ, không ảnh hưởng đến dấu tích (tick mark)- Để tùy chỉnh hoàn toàn giao diện CheckBox (tick, background), nên sử dụng
android:buttonTint(API 21+) hoặc drawable selector setBackgroundColor()thay đổi nền toàn bộ view bao gồm cả vùng tick- Cách tốt hơn: định nghĩa style/theme trong XML cho nhất quán
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Nhấn nút "Đổi màu" để thay đổi màu chữ và nền CheckBox.

