Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding TextViews to home screen widget programmatically

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);
like image 767
kkgery Avatar asked Dec 04 '22 05:12

kkgery


1 Answers

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

like image 189
Seth Avatar answered Jan 30 '23 13:01

Seth