如何在 Android Studio Widget 中更新多个远程视图

How to update more than one Remote View in Android Studio Widget

这是我的小部件代码

class MovieOfTheDayWidget : AppWidgetProvider() {
    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)
        }
    }

    override fun onEnabled(context: Context) {
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}

internal fun updateAppWidget(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetId: Int,
) {

    val randomMovieList = Constants.getAllMovies()
    val movie: AllMovies
    val randomMovieListSize = randomMovieList.size
    var randomPosition = Random().nextInt(randomMovieListSize)

    movie = randomMovieList[randomPosition]

    val idArray = arrayListOf<RemoteViews>()

    // Construct the RemoteViews object
    val movieName = RemoteViews(context.packageName, R.layout.movie_of_the_day_widget)
    movieName.setTextViewText(R.id.seriesMovieNameAndYearWidget, "${movie.movieName} (${movie.date}")

    val movieImg = RemoteViews(context.packageName, R.layout.movie_of_the_day_widget)
    movieImg.setImageViewResource(R.id.seriesMovieImgWidget, movie.moviePic)

    val movieRating = RemoteViews(context.packageName, R.layout.movie_of_the_day_widget)
    movieRating.setTextViewText(R.id.seriesMovieRatingWidget, movie.rating)

    idArray.add(movieName)
    idArray.add(movieRating)
    idArray.add(movieImg)
    
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, idArray[0])
    appWidgetManager.updateAppWidget(appWidgetId, idArray[1])
    appWidgetManager.updateAppWidget(appWidgetId, idArray[2])

}

但是最后 3 行不能正常工作,只有第二行可以,如何更新 idArray 中的所有 RemoteViews。 我试过将它放入 for 循环并更新 i,但它也没有用。 不止一次调用 updateAppWidget 函数是正确的做法吗?我试过将多个参数传递给该函数,但它返回了一个错误。

你是对的,appWidgetManager.updateAppWidget()应该只调用一次。

您需要将所有更改应用到同一个 RemoteViews 实例,因此它应该是:

// Construct the RemoteViews object
val remoteViews = RemoteViews(context.packageName, R.layout.movie_of_the_day_widget)

remoteViews.setTextViewText(R.id.seriesMovieNameAndYearWidget, "${movie.movieName} (${movie.date}") 
remoteViews.setImageViewResource(R.id.seriesMovieImgWidget, movie.moviePic)
remoteViews.setTextViewText(R.id.seriesMovieRatingWidget, movie.rating)

// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, remoteViews)