0
点赞
收藏
分享

微信扫一扫

Kotlin 自定义 View

瑾谋 2022-01-27 阅读 80
kotlin

自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomPagerTab">
        <attr name="textColor" format="color"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
</resources>

 创建自定义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)
        }
}

布局中应用自定义属性

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <com.cniao5.common.widget.CustomPagerTab
            app:textColor="@color/colorPrimary"
            app:textSize="16sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </androidx.viewpager2.widget.ViewPager2>
</LinearLayout>
举报

相关推荐

0 条评论