我需要在LinearLayout内部的POST请求完成后,动态地向fragment添加视图。
下面是我的函数,它创建并设置视图并返回它,然后通过addView()方法将其添加到addView()中。没有例外,但没有添加视图。
经过一些调试,我注意到在logcat中只有一条消息“横幅created1”而没有消息“created2",就像程序在加载颜色资源时冻结了一样。
Log.d("VIEW", "Banner created1") // appears in logcat
val colorFrom = resources.getColor(R.color.banner_regular, null)
Log.d("VIEW", "Banner created2") // not appears in logcatprivate fun generateBanner(chatData: ChatData):View? {
val banner = inflater.inflate(R.layout.chat_banner, null, false)
banner.run {
findViewById<TextView>(R.id.user_name).text = chatData.name
findViewById<TextView>(R.id.short_code).text = chatData.shortCode
findViewById<TextView>(R.id.short_message).text =
chatData.lastMessage.let { it.substring(0, min(40, it.length)) + "..." }
findViewById<ImageView>(R.id.unread_dot).visibility =
if (chatData.hasUnread) VISIBLE else GONE
findViewById<TextView>(R.id.date_time_text).text = chatData.lastMessageTime
}
Log.d("VIEW", "Banner created1")
val colorFrom = resources.getColor(R.color.banner_regular, null)
Log.d("VIEW", "Banner created2")
val colorTo = resources.getColor(R.color.banner_clicked, null)
val animation = ValueAnimator.ofObject(
ArgbEvaluator(), colorFrom, colorTo, colorFrom
).apply {
addUpdateListener {
banner.setBackgroundColor(animatedValue as Int)
}
}
banner.setOnClickListener {
animation.start()
openChat(chatData.uid)
}
return banner
}generateBanner()在这里被称为,同样的情况:顶部被打印,底部没有
private fun addChatsToRoot(chats:List<ChatData>) {
Log.d("VIEW", "Adding chats to root") // printed to logcat
for(chatData in chats) {
chatsData += chatData.uid to chatData
val banner = generateBanner(chatData)
chatsRoot.addView(banner)
}
Log.d("VIEW", "Chats are added to the layout") // not in logcat
}我尝试删除主题的null参数,没有什么改变。我还将resources调用更改为表示白色颜色的原始数字,创建了布局,没有冻结代码,但是布局膨胀错误,banner.height总是为零,即使在它的可绘制文件中设置了minHeight。
所以看起来我不能从这个片段加载任何类型的资源
发布于 2022-06-27 12:06:18
尝尝这个
ContextCompat.getColor(applicationContext,R.color.banner_regular)发布于 2022-06-27 14:43:56
原来所有的问题都是因为我在另一个碎片里有一个碎片。这不仅造成了资源访问方面的问题,而且还导致了其他布局视图的膨胀。
我的解决方案是将片段移动到一个级别,并使用一个navController导航。
https://stackoverflow.com/questions/72771446
复制相似问题