2010-11-02 50 views
8

我有一個應用程序小部件,我想向RemoteView添加視圖(TextView等),但它永遠不會顯示。
這裏去代碼:RemoteView addView無法正常工作

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 
RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout); 
    newView.setTextViewText(R.id.textUser, "1234"); 
    views.addView(views.getLayoutId(), newView); 
// Tell the AppWidgetManager to perform an update on the current App Widget 
appWidgetManager.updateAppWidget(appWidgetId, views); 

任何想法?


這是我落得這樣做:

RemoteViews newView = new RemoteViews(context.getPackageName(), R.layout.widget_row_layout); 
    newView.setTextViewText(R.id.textUser, "1234"); 
ComponentName thisWidget = new ComponentName(this,WidgetProvider.class); 
AppWidgetManager manager = AppWidgetManager.getInstance(this); 
    manager.updateAppWidget(thisWidget, newView); 
+1

您應該將解決方案作爲答案添加並標記爲答案或選擇現有答案作爲解決方案。否則,這只是掛在那裏,因爲沒有回答... – 2010-11-27 23:48:07

+1

是的,我同意hambonious,將其標記爲答案,並給這個人一些功勞! – JPM 2011-10-03 14:42:05

回答

25

的addView()方法需要裏面的佈置要將此新視圖添加到視圖的ID,而不是佈局本身。

取而代之的是:

views.addView(views.getLayoutId(), newView); 

試試這個:

views.addView(R.id.view_container, newView); 

假設您的佈局看起來是這樣的:

文件:佈局/ widget_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <LinearLayout 
     android:id="@+id/view_container" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
     <!-- New views will be added here at runtime --> 
    </LinearLayout> 
</LinearLayout> 
+0

這就是我最終做的: – 2010-11-21 14:33:21

+0

太棒了!這正是我需要的。非常感謝。 – Hubert 2011-05-20 04:07:19

+1

優秀的答案尊重++。 – 2011-11-28 21:32:18