Kotlin 自定义 View

自定义属性



    
        
        
    

 创建自定义View,并解析属性

自定义视图要在类名后面增加 @JvmOverloads constructor 因为布局文件中的自定义视图必须兼容Java

class CustomPagerTab 
    @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null,defStyleAttr: Int = 0) :
    PagerTabStrip(context,attributeSet) {

        private var textColor = Color.Black
        private var textSize = 15
        init {
           
            if (attributeSet!=null){
                // 解析自定义属性
                val typedArray:TypedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CustomPagerTab)
                textColor =  typedArray.getColor(R.styleable.CustomPagerTab_textColor,textColor)
                textSize = typedArray.getDimensionPixelSize(R.styleable.CustomPagerTab_textSize,textSize)
                typedArray.recycle()
            }

            // 设置属性
            setTextColor(textColor)
            setTextSize(TypedValue.COMPLEX_UNIT_SP,textSize)
        }
}

布局中应用自定义属性



    
        
    

你可能感兴趣的:(kotlin,kotlin)