Giới thiệu
Hướng dẫn tải và hiển thị ảnh từ URL vào ImageView bằng thư viện Picasso (Square) - thư viện load ảnh phổ biến, đơn giản, mạnh mẽ.
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: Thêm dependency Picasso (build.gradle Module: app)
dependencies {
// ... dependencies khác
implementation 'com.squareup.picasso:picasso:2.71828' // Phiên bản mới nhất ổn định
}
Nhấn Sync Now để tải thư viện.
Bước 3: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load ImageView từ URL"
android:textStyle="bold"
android:textColor="@color/colorPrimary"
android:textSize="20sp" />
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
android:contentDescription="Ảnh từ URL" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="24sp"
android:gravity="center|bottom"
android:textStyle="bold" />
</LinearLayout>
Bước 4: Load ảnh với Picasso (src/MainActivity.java)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image_view);
String url = "https://images.pexels.com/photos/814499/pexels-photo-814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
// One-liner load ảnh
Picasso.get().load(url).into(imageView);
}
}
Bước 5: AndroidManifest.xml (cần quyền INTERNET)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
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ị (có internet), nhấn Run. Ảnh từ URL sẽ load hiển thị trong ImageView.

Tính năng nâng cao của Picasso
1. Placeholder & Error Image
Picasso.get()
.load(url)
.placeholder(R.drawable.placeholder) // Ảnh chờ load
.error(R.drawable.error_image) // Ảnh khi load thất bại
.into(imageView);
2. Resize & Transform
Picasso.get()
.load(url)
.resize(400, 400) // Resize chính xác
.centerCrop() // Crop giữa
.rotate(90) // Xoay 90 độ
.transform(new CircleTransform()) // Bo tròn (custom transform)
.into(imageView);
3. Callback xử lý thành công/thất bại
Picasso.get().load(url).into(imageView, new Callback() {
@Override public void onSuccess() { Log.d("Picasso", "Load thành công"); }
@Override public void onError(Exception e) { Log.e("Picasso", "Load lỗi", e); }
});
4. Cache Policy
Picasso.get()
.load(url)
.networkPolicy(NetworkPolicy.OFFLINE) // Chỉ dùng cache
.memoryPolicy(MemoryPolicy.NO_CACHE) // Bỏ qua memory cache
.into(imageView);
5. Target tùy chỉnh (không phải ImageView)
Target target = new Target() {
@Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
// Xử lý bitmap tùy ý
}
@Override public void onBitmapFailed(Exception e, Drawable errorDrawable) {}
@Override public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
Picasso.get().load(url).into(target);
// QUAN TRỌNG: Giữ strong reference đến target để không bị GC!
So sánh thư viện load ảnh
| Thư viện | Ưu điểm | Nhược điểm |
|---|---|---|
| Picasso | API đơn giản, ít config, tự handle recycle | Ít tùy chỉnh nâng cao, chậm hơn Glide một chút |
| Glide | Nhanh, hỗ trợ GIF/Video, tích hợp lifecycle, nhiều transform | API phức tạp hơn, size lớn hơn |
| Coil (Kotlin) | Coroutines first, lightweight, Kotlin idiomatic | Chỉ Kotlin, mới hơn |
| Fresco | Quản lý memory tốt (ashmem), progressive JPEG | Setup phức tạp, size lớn |
Lưu ý
- Luôn thêm quyền
INTERNETtrong Manifest - Picasso 2.71828+ dùng
Picasso.get()thayPicasso.with(context)(deprecated) - Để load ảnh local:
Picasso.get().load(new File(path)).into(imageView)hoặcload("file:///path") - Cân nhắc dùng
Coilcho project Kotlin mới