kotlin 动态绘制

通过这篇文章你可以学习到:
如何使用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()
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值