Hướng dẫn này minh họa cách gộp chồng hai hình ảnh (overlay/merge) bằng layer-list drawable và hiển thị kết quả lên ImageView.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project.
Bước 2: Giao diện chính (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"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnOverlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="OverLayImage"
android:text="Chồng hình ảnh"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnOverlay"/>
</RelativeLayout>
Bước 3: Tạo layer-list drawable (res/drawable/layer.xml)
Đặt hai hình ảnh cần chồng (ví dụ: image.png và image1.png) vào thư mục res/drawable/.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image" />
<item android:drawable="@drawable/image1" />
</layer-list>
Lưu ý: Thứ tự item quyết định thứ tự z-index — item sau sẽ nằm trên item trước.
Bước 4: Activity (src/MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
}
public void OverLayImage(View view) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.layer));
}
}
Bước 5: 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>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Nhấn nút "Chồng hình ảnh" để xem kết quả hai ảnh được gộp nhau.