2014-08-31 198 views
1

我試圖將影像在我的窗口小部件設置爲一個ImageView的,但不是圖片我有一個空的屏幕RemoteView.setImageViewResource不顯示任何

這裏的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical"> 
<ImageView 
    android:id="@+id/stage" 
    android:layout_width="match_parent" 
android:layout_height="match_parent" 

    /> 
</RelativeLayout> 

這裏的代碼:

public class MyWidget extends AppWidgetProvider { 

     Bitmap bitmap; 
     Bitmap bckgrnd; 
     Bitmap over; 

     @Override 
     public void onEnabled(Context context) { 
     super.onEnabled(context); 

RemoteViews widgetView = new RemoteViews(context.getPackageName(), 
       R.layout.widget); 
     bckgrnd=BitmapFactory.decodeResource(context.getResources(), R.drawable.backgrnd); 
     over=BitmapFactory.decodeResource(context.getResources(), R.drawable.human); 

     bitmap=bckgrnd.copy(Bitmap.Config.ARGB_8888, true);; 
     Canvas c=new Canvas(bitmap); 
     c.drawBitmap(over, 50, 50, new Paint()); 
     widgetView.setImageViewBitmap(R.id.stage, bitmap); 



     Log.d("MyLog", "onEnabled"); 
     } 

    ...... 
    } 

所以,我的「OnEnabled」一登錄我的logcat這意味着該代碼已經被執行良好,但ImageView的保持爲空。如果我在佈局xml中設置任何圖像 - 它會顯示圖像,這意味着xml設置正確,但代碼不會更改ImageView中的此圖像。

我試圖在onUpdate()中做到這一點,但它也沒有工作。 我該怎麼做才能在ImageView中更改此圖像?

+0

您在設置圖像後是否調用過appWidgetManager.updateAppWidget方法? – hoomi 2014-08-31 08:37:48

+0

appWidgetManager.updateAppWidget(new ComponentName(context,MyWidget.class),widgetView); - 這是正確的嗎?我從onUpdate()調用它,但沒有任何反應 – 2014-08-31 08:55:28

+0

'public void partiallyUpdateAppWidget(int appWidgetId,RemoteViews views)''?從你的代碼中感覺到,當你改變圖像時,你忘了通知AppWidgetManager – hoomi 2014-08-31 09:03:34

回答

1

我認爲它現在已經晚了......但只是爲了幫助仍在尋找的人。

對於我來說,這個工作..

// Change widget image, and update current app widget. 
widgetView.setImageViewBitmap(R.id.stage, bitmap); 
AppWidgetManager.getInstance(context).updateAppWidget(COMPONENT_NAME, widgetView); 

而且,COMPONENT_NAME

COMPONENT_NAME = new ComponentName(context, MyWidget.class); 

如果你只想在單擊是控件這將更新您的應用程序..每一個部件更新,然後通過其widgetId代替COMPONENT_NAMEupdateAppWidget()

+0

http://developer.android.com/reference/android/widget/ImageView.html#setImageResource(int) – CrandellWS 2016-02-13 11:26:39

+0

這會在UI線程上進行位圖讀取和解碼,這會導致延遲打嗝。如果這是一個問題,請考慮使用setImageDrawable(android.graphics.drawable.Drawable)或setImageBitmap(android.graphics.Bitmap)和BitmapFactory代替。 – CrandellWS 2016-02-13 11:27:02

1

我遇到過和你一樣的類似問題,除了我在onUpdate的後續調用中調用rv.setImageViewResource。

我的解決方案是,您必須在xml文件中設置ImageView的初始圖像,然後您可以在運行時更改ImageView;如果你沒有在xml中指定最初的圖片,那麼setImageViewResource不起作用,ImageView什麼也不顯示。

更新:

現在setImageViewResource效果很好,無論ImageView的在XML初始SRC與否,它雖然有線。