通过这篇文章你可以学习到:
如何使用kotlin,来实现界面元素的动态绘制。以及寻找到相关控件元素进行对应赋值
废话不多说,直接上代码:
(很简单的一个小demo,实现一个三行三列的列表,并将数据元素展示)
class DynamicMapping : LinearLayout{
constructor(context: Context): super(context)
constructor(context: Context, attributeSet: AttributeSet): super(context,attributeSet)
//全局的布局
private var totalLayout = LinearLayout(context)
private var arr = arrayOf(1,2,3,4,5,6,7,8,9)
init {
//主布局
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)
orientation = VERTICAL
gravity = Gravity.CENTER
setBackgroundColor(Color.parseColor("#FFFFFF"))
//绑定视图内容
initView()
initData(arr)
}
private fun initView(){
//动态绘制实现三行三列的表格视图
totalLayout = LinearLayout(context)
totalLayout.layoutParams = LayoutParams(300,360)
totalLayout.orientation = VERTICAL
addView(totalLayout)
//创建三行
for(line in 0 until 3){
val linearLayout = LinearLayout(context)
//固定控件的大小
linearLayout.layoutParams = LayoutParams(300,100)
linearLayout.setBackgroundColor(Color.parseColor("#ccffff"))
//设置控件的间距
(linearLayout.layoutParams as LayoutParams).setMargins(0,20,0,0)
totalLayout.addView(linearLayout)
//创建三列
for(col in 0 until 3){
val textView = TextView(context)
textView.layoutParams = LayoutParams(100,LayoutParams.MATCH_PARENT)
textView.setBackgroundColor(Color.parseColor("#33ffff"))
textView.gravity = Gravity.CENTER
textView.textSize = 30f
linearLayout.addView(textView)
}
}
}
private fun initData(arr : Array<Int>){
for(i in 0 until totalLayout.childCount){
//首先遍历寻找到行的个数
val linearLayout = totalLayout.getChildAt(i) as LinearLayout
//再遍历寻找到行中列的个数
for(j in 0 until linearLayout.childCount){
val textView = linearLayout.getChildAt(j) as TextView
textView.text = arr[ i * 3 + j].toString()
}
}
}
}