Thêm icon vào Widget

Hiện tại em muốn chèn 1 icon vào home screen widget. Icon này nằm trong drawable của android studio.
Bình thường em dùng để chèn image thì em dùng drawable nhưng ở RemoteViews ở widget không có setImageDrawable.
Đây là hàm Update ở trong AppWidgetProvider em viết để update image vào widget. Nhưng khi chạy thì không hiện gì ở widget cả, cũng không có lỗi ở logcat.

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for(int appWidgetId : appWidgetIds){
        RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget);

        String icon_uri = "/drawable/test_icon"; // icon này dùng imageview ở MainActivity hoạt động bình thường. Đuôi png
        int imageResource = context.getResources().getIdentifier(icon_uri, null, context.getPackageName());
        views.setImageViewResource(R.id.icon_wid, imageResource);
        appWidgetManager.updateAppWidget(appWidgetId,views);
    }
}

Đây là file icon_wid.xml

 <?xml version="1.0" encoding="utf-8"?>                                          
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#A580E6">


<ImageView
    android:id="@+id/icon_wid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_launcher_foreground" />
</RelativeLayout>

Nếu thay ImageView bằng Textview thì set lại bình thường.
Mọi người giúp em với ạ. Cảm ơn.

Ý bạn là bạn gán hình cho TextView???

Bạn có chắc là dòng context.getResources().getIdentifier(...) đã lấy được đúng định danh cho tài nguyên cần lấy? Bạn thử in giá trị ra xem thử (logcat), nếu là 0 thì tài nguyên không tìm thấy rồi.
Từ tài liệu: https://developer.android.com/reference/android/content/res/Resources#getIdentifier(java.lang.String,%20java.lang.String,%20java.lang.String)
Lấy định danh từ tên phải theo cấu trúc: package:type/name, hình như bạn dư dấu / thì phải.

/drawable/icon
drawable/icon
2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?