2012-02-13 123 views
4

我想以編程方式添加文本視圖控件到我的主屏幕小部件。在下面的示例中,我使用TextView填充了Linearlayout,但我應該如何在這裏使用RemoteViews?它只接受xml資源佈局作爲參數。添加TextViews到主屏幕小部件編程

public class MyWidget extends AppWidgetProvider { 
    public void onUpdate(Context _context, AppWidgetManager appWidgetManager, 
         int[] appWidgetIds) { 

     LinearLayout l = new LinearLayout(_context); 

     for (int i = 0; i < 10; i++) { 
      TextView t = new TextView(_context); 
      t.setText("Hello"); 
      l.addView(t); 
     } 
    } 
} 

所有教程只見明確填充RemoteViews與它預定義控件的值對象。我想添加控制programmaticaly。

RemoteViews views = new RemoteViews(context.getPackageName(), 
R.layout.my_widget); 
views.setTextViewText(R.id.widget_control1, value1); 
views.setTextViewText(R.id.widget_control2, value2); 

回答

3

好吧,這對appwidgets是不可能的。只有xml資源被接受。

0

你可以試試這個

LinearLayout l = new LinearLayout(_context); 

for (int i = 0; i < 10; i++) { 
TextView t = new TextView(this); 
t.setText("Hello"); 
t.setBackgroundColor(Color.RED); 
t.setSingleLine(true); 
l.addView(t); 
} 

l.setId(100) 

RemoteViews views = new RemoteViews(context.getPackageName(),100); 
views.setTextViewText(R.id.widget_control1, value1); 
views.setTextViewText(R.id.widget_control2, value2); 
+0

謝謝,我編輯我的問題一點,我的觀點是,我應該如何處理RemoteViews,因爲它似乎管理部件佈局。如果我調用setContentView(l),我是否也應該在某處調用RemoteViews? – kkgery 2012-02-13 19:40:56

+0

爲此目的,你不需要。 – 2012-02-13 19:51:36

+1

它似乎沒有工作。 SetContentView是爲Activities類定義的,而不是爲AppWidgetProvider定義的。如果我從窗口小部件Activity類中調用它,它會創建一個新窗口(活動)並在其中填充控件。那麼,我需要從擴展AppWidgetProvider的類的Update方法中調用RemoteViews嗎?或者有一種方法可以以某種方式使用setcontentview? – kkgery 2012-02-14 14:18:58

9

在尋找我自己的答案偶然發現了這個問題,雖然這並沒有回答我的問題,我想我會回答這個問題。

假設你已經有一個小部件,test.xml佈局文件。

現在,創建一個新的佈局,例如保存到text_view_layout.xml。在這種佈局xml有這個作爲它的內容:

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="TextView" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

你現在剛創建了一個佈局,其根視圖是一個文本視圖。

現在在你的代碼,你可以添加文字這個文本視圖像這樣:

RemoteViews update = new RemoteViews(getPackageName(), R.layout.test); 
for(int i = 0; i < 3; i++) { 
    RemoteViews textView = new RemoteViews(getPackageName(), R.layout.text_view_layout); 
    textView.setTextViewText(R.id.textView1, "TextView number " + String.valueOf(i)); 
    update.addView(R.id.linearLayout1, textView); 
} 

mAppWidgetManager.updateAppWidget(mAppWidgetId, update); 

現在你只創建了三個textViews所有文字是「TextView的0號」等等...

我敢肯定有一個類似的答案其他地方,但是這是如何以編程方式添加textViews到appWidget。

RemoteViews API