Adding TextViews to home screen widget programmatically

守給你的承諾、 提交于 2019-12-05 16:32:29
Seth

Stumbled upon this question in searching for my own answer, and while this doesn't answer my question i figured i would answer this question.

Assuming you already have a layout file for your widget, test.xml.

Now, create a new layout, save e.g. to text_view_layout.xml. In that layout xml have this as its contents:

<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" />

You now just created a layout with its root view being a text view.

Now in your code you can add text to this text view like so:

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);

Now you just created three textViews all with the text being "TextView number 0" and so on...

I'm sure there is a similar answer somewhere else, but this is how to programmatically add textViews to an appWidget.

RemoteViews API

Ok, It is impossible for appwidgets. Only xml resources are accepted.

You could try this

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!