小部件列表视图不显示任何内容

时间:2020-10-04 00:00:46

标签: android listview kotlin android-widget

我无法在Android的Widget中显示ListView,由于某种原因,(空)Widget不会显示出来,除非在进行调试时否则不会占据主屏幕上的空间。如果我在填充ListView的末尾进行调试,它将正确显示。

这是我的代码:

AppWidgetProvider

override fun onUpdate(
    context: Context?,
    appWidgetManager: AppWidgetManager?,
    appWidgetIds: IntArray?
) {
    appWidgetIds?.forEach { appWidgetId ->
        var remoteViews = RemoteViews(context?.packageName, R.layout.template_widget_news)
        val intent = Intent(context, NewsWidgetViewsService::class.java)
        remoteViews.setRemoteAdapter(R.id.widget_recyclerview, intent)
        appWidgetManager?.updateAppWidget(appWidgetId, remoteViews)
    }
}

RemoteViewsService

class NewsWidgetViewsService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
    return NewsWidgetProvider(applicationContext, intent)
}}

NewsWidgetProvider

override fun onCreate() {
    initWidgetData()
}
private fun initWidgetData() {
    var authoritation = ""
    localData = LocalData.getInstance(context)
    if (Locale.getDefault().displayLanguage.toLowerCase() == m.english) {
        lenguaje = "en"
    }
    context.getSharedPreferences(Constants.appPreferences, Context.MODE_PRIVATE)
        ?.getString(Constants.accessToken, "")?.let { tokenSession ->
        if (tokenSession.isNotEmpty()) {
            authoritation = tokenSession
        }
    }
    serverClient = ServerClient(
        context,
        authoritation,
        Utilies.getConstant(context.getString(R.string.a)),
        lenguaje,
        409,
        this
    )

    NewsRepository.processNewData(
        context,
        serverClient,
        localData
    ) { success: Boolean, requestedNewsData: ArrayList<Entity.New>? ->
        if (success && !requestedNewsData.isNullOrEmpty()) {
            news = requestedNewsData
        } else {
            Log.d("WIDGET", "FUNCIONÓ PERO SE MURIÓ")
        }
    }
}

override fun getCount(): Int {
    return if(!news.isNullOrEmpty()){
        news?.count()!!
    } else {
        0
    }
}
override fun getViewAt(position: Int): RemoteViews? {
    if(position == AdapterView.INVALID_POSITION || news == null) {
        return null
    }
    var remoteViews = RemoteViews(context?.packageName, R.layout.cardview_widget_news)
    remoteViews.setTextViewText(R.id.widget_title, news?.get(position)?.title)
    remoteViews.setTextViewText(R.id.widget_subtitle, news?.get(position)?.subtitle)
    return remoteViews
}

即使我的listview元素称为cardview,我内部也没有cardview,但我查看了Android文档,知道了可以在XML中使用的小部件。

重申,出于某种未知的原因,除非我使用F8进行流程调试,否则不会显示小部件的列表视图。

有人可以给我建议吗?拜托,谢谢。

0 个答案:

没有答案