Giới thiệu
Hướng dẫn này trình bày cách tạo hình nền (background) lặp lại (tile/repeat) cho toàn bộ ứng dụng Android sử dụng bitmap drawable và theme.
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: Tạo drawable background lặp (res/drawable/app_background.xml)
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
android:src="@drawable/image1"
android:tileMode="repeat" />
Các giá trị tileMode:
repeat- Lặp cả ngang và dọc (mặc định)mirror- Lặp và gương chiếu (tạo hiệu ứng liên tục mượt)clamp- Không lặp, kéo giãn pixel rìadisabled- Không lặp
Bước 3: Cấu hình Theme (res/values/styles.xml)
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- Áp dụng background lặp cho toàn bộ cửa sổ -->
<item name="android:windowBackground">@drawable/app_background</item>
</style>
</resources>
Bước 4: 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp" />
Bước 5: Logic chính (src/MainActivity.java)
package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Không cần code thêm, background đã được áp dụng qua theme
}
}
Bước 6: 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 ý
- File ảnh
image1.png/jpgcần đặt trongres/drawable/ - Ảnh nên là seamless (liền mạch) để hiệu ứng lặp đẹp
- Kích thước ảnh nhỏ (ví dụ 100x100dp) sẽ lặp nhiều lần, ảnh lớn lặp ít lần
- Áp dụng ở theme cấp ứng dụng (
android:windowBackground) sẽ ảnh hưởng tất cả Activity - Có thể áp dụng cho từng View:
android:background="@drawable/app_background"
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Toàn bộ nền ứng dụng sẽ hiển thị hình ảnh lặp lại.
