Android - LinearView - 视图的动态实例化 [英] Android - LinearView - Dynamic instanciation of views
本文介绍了Android - LinearView - 视图的动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建在线性布局中实例化某些视图的函数
I am trying to create functions that instanciate some views in a Linear Layout
private lateinit var layout: LinearLayout
var par = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
override fun onCreate(savedInstanceState: Bundle?) {
//The init stuff with binding
layout = binding.root.findViewById(R.id.gamelayout)
lpar.setMargins(10,10,10,10)
test()
}
private fun instanciateText(s:String)
{
val tv = TextView(this)
tv.text = s
tv.layoutParams = par
layout.addView(tv)
}
fun instanciateImage()
{
val iv = ImageView(this)
iv.setImageResource(R.drawable.start1)
iv.layoutParams = par
layout.addView(iv)
}
fun test(){
instanciateText("Text 1 ")
instanciateImage()
instanciateText("Text 2 ")
}
它适用于文本,但对于图像,视图彼此相距很远,我找不到原因
It works fine with text, but whith images, the views are so far from each other, and i cannot find why
推荐答案
如果添加了一个可拉伸的 ImageView,它会被扩展到最大程度,以便 LinearLayout 得到 100% 的子元素填充.这是正确的行为.如果您想避免这种情况,请指定 ImageView.adjustViewBounds = true.
If a stretchable ImageView is added, it is to be expanded to the maximum extent so the LinearLayout gets 100%-filled with children. It's right behavior. If you'd like to avoid that, specify ImageView.adjustViewBounds = true.
fun instanciateImage()
{
val iv = ImageView(this)
iv.setImageResource(R.drawable.start1)
iv.layoutParams = par
iv.adjustViewBounds = true
layout.addView(iv)
}
这篇关于Android - LinearView - 视图的动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文