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

Cách truyền Drawable giữa các Activity trong Android

Giới thiệu

Ví dụ này minh họa cách truyền resource ID của drawable (không phải bitmap object) giữa hai Activity qua Intent extra.

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 chính (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">
    <Button
        android:id="@+id/button"
        android:text="Chuyển Bitmap sang Activity 2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

Bước 3: MainActivity.java - Gửi resource ID

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                // Truyền resource ID (int) thay vì Bitmap object
                intent.putExtra("picture", R.drawable.ic_directions_walk);
                startActivity(intent);
            }
        });
    }
}

Bước 4: SecondActivity.java - Nhận và set image

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class SecondActivity extends AppCompatActivity {
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        imageView = findViewById(R.id.imageView);
        Bundle bundle = getIntent().getExtras();
        
        if (bundle != null) {
            int picture = bundle.getInt("picture");
            imageView.setImageResource(picture);
        }
    }
}

Bước 5: Layout Activity 2 (activity_second.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=".SecondActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity Thứ Hai"
        android:layout_marginTop="25sp"
        android:layout_centerHorizontal="true"
        android:textSize="16sp"
        android:textStyle="bold"/>
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

Bước 6: 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=".SecondActivity"></activity>
        <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 để chuyển sang Activity 2 hiển thị icon drawable.

Cách truyền Drawable giữa các Activity trong Android

Cách truyền Drawable giữa các Activity trong Android

Tại sao truyền resource ID thay vì Bitmap?
  • Bitmap chiếm nhiều bộ nhớ, dễ gây OOM nếu truyền qua Intent (giới hạn ~1MB)
  • Resource ID chỉ là int (4 bytes), nhẹ và an toàn
  • Cả hai Activity cùng truy cập resource của app, không cần serialize
Nếu bắt buộc truyền Bitmap: Dùng intent.putExtra("bitmap", bitmap) (Bitmap implements Parcelable) hoặc lưu file tạm/cache và truyền đường dẫn.