解析 view 自定义属性

5年以前  |  阅读数:1038 次  |  编程语言:Kotlin 

这里的核心是 kotlin 对 list 的写法和 Sequence 序列的应用,Sequence 序列会大大提升 list 处理速度,rxjava 式的调用感官是很 Nice 的。

private fun initAttrs(context: Context, attributeSet: AttributeSet?, defAttrStyle: Int) {
        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CustomeTextView)
        (0..typedArray.indexCount)
                .asSequence()
                .map { typedArray.getIndex(it) }
                .forEach {
                    when (it) {
                    // 获取文字内容
                        R.styleable.CustomeTextView_android_text -> {
                            mText = typedArray.getString(R.styleable.CustomeTextView_android_text)
                        }
                    // 获取文字大小
                        R.styleable.CustomeTextView_android_textSize -> {
                            var textSize = typedArray.getDimensionPixelSize(R.styleable.CustomeTextView_android_textSize, 0).toFloat()
                            mPaint.textSize = textSize
                        }
                    }
                }
        typedArray.recycle()
    }

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8