Senior Software Engineer @ Acorns
// Find the widget id from the intent.
intent.extras?.let { extras ->
appWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
}
// If this activity was started without an app widget ID, finish with an error.
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
setResult(RESULT_CANCELED)
finish()
return
}
// Configuration activity updates the app widget
val appWidgetManager = AppWidgetManager.getInstance(context)
updateAppWidget(context, appWidgetManager, appWidgetId)
// Make sure we pass back the original appWidgetId
val resultValue = Intent()
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
setResult(RESULT_OK, resultValue)
finish()
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
val widgetText = loadTitlePref(context, appWidgetId)
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.test_widget)
views.setTextViewText(R.id.appwidget_text, widgetText)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:configure="org.ocandroid.widgetplayground.widget.TestWidgetConfigureActivity"
android:description="@string/app_widget_description"
android:initialKeyguardLayout="@layout/test_widget"
android:initialLayout="@layout/test_widget"
android:minWidth="40dp"
android:minHeight="40dp"
android:previewImage="@drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="86400000"
android:widgetCategory="home_screen" />
// Listen for check changes. The intent will have an extra with the key
// EXTRA_CHECKED that specifies the current checked state of the view.
remoteView.setOnCheckedChangeResponse(
R.id.my_checkbox,
RemoteViews.RemoteResponse.fromPendingIntent(onCheckedChangePendingIntent)
)
remoteView.setRemoteAdapter(
R.id.list_view,
RemoteViews.RemoteCollectionItems.Builder()
.addItem(/* id= */ ID_1,
RemoteViews(R.layout.item_type_1))
.addItem(/* id= */ ID_2,
RemoteViews(R.layout.item_type_2))
...
.setViewTypeCount(itemLayouts.count())
.build()
)
// Set the colors of a progress bar.
remoteView.setColorStateList(
R.id.progress,
"setProgressTintList",
createProgressColorStateList()
)
// Specify exact sizes for margins.
remoteView.setViewLayoutMargin(
R.id.text,
RemoteViews.MARGIN_END,
8f,
TypedValue.COMPLEX_UNIT_DP
)