我有一个简单的Kotlinandroid应用程序,其中有一个GridLayout视图,然后我通过编程向其中添加视图。如果我只是在onCreate方法中调用它,这将工作得很好:
findViewById<GridLayout>(R.id.gridLayout).addView(Button(this))
但是如果我在另一个线程中调用它,在我的例子中,它是在forEach
循环中的CompletableFuture.runAsync
中,它将停止工作。我尝试使用LayoutInspector查看,但是没有视图被添加到GridLayout。我还尝试调试,看看代码是否已经到达,是的,我还尝试在onCreate中保存Context
,以便在其他线程中重用它来创建视图,但也没有成功。
有人遇到过类似的问题吗?
这是一段不起作用的代码:
val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
savedPics.forEach { (picture, bytearray) ->
val cardView = CardView(context)
val param = GridLayout.LayoutParams(
GridLayout.spec(
GridLayout.UNDEFINED, GridLayout.FILL, 1f
),
GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f)
)
param.height = 0
param.width = 0
cardView.layoutParams = param
val verticalLinearLayour = LinearLayout(context)
verticalLinearLayour.layoutParams =
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
verticalLinearLayour.orientation = LinearLayout.VERTICAL
val imageView = ImageView(context)
val bitmap = BitmapFactory.decodeByteArray(bytearray, 0, bytearray.size)
imageView.setImageBitmap(bitmap)
val textView = TextView(context)
textView.layoutParams = LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)
textView.text = picture.image_name
verticalLinearLayour.addView(imageView)
verticalLinearLayour.addView(textView)
cardView.addView(verticalLinearLayour)
cardView.setOnClickListener {
val intent = Intent(context, ViewPicture::class.java)
intent.putExtra("picture", picture)
intent.putExtra("image_array", bytearray)
startActivity(intent)
}
gridLayout.addView(verticalLinearLayour)
}
1条答案
按热度按时间8hhllhi21#
好的,问题是它没有被添加到UI线程中。要使它在UI线程中运行,只需使用
runOnUiThread
。太糟糕了,甚至没有错误消息或任何指示错误操作的东西。