I want to programmatically add Text Views controls to my home screen widget. In the following example I populate Linearlayout with TextViews, but how should I use RemoteViews here? It only accepts xml resource layout as a parameter.
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);
}
}
}
All tutorials I saw explicitly populate RemoteViews object with values for its predefined controls. And I want to add controls 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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With