美文网首页
Android 自定义属性

Android 自定义属性

作者: 没有了遇见 | 来源:发表于2022-07-11 10:07 被阅读0次

背景

有时候Android 提供的原生View TextView等不满足我们的需要,或者自己自定义的一些View 为了扩展一些自己的需求我们会重新定义一些函数.这些函数从xml中获取一些配置内容,这个时候我们就需要用到自定义属性这方面的内容.

自定义属性实现的步骤

1.在res/values/attrs.xml中配置View的自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="FlowLayoutStyle">
        <!--        Labels的文字-->
        <attr name="flTextColor" format="color" />
        <!--        Labels的背景色-->
        <attr name="flBackgroundColor" format="color" />
        <!--        Labels的角度大小-->
        <attr name="flAngleSize" format="float" />
        <!--        Labels的左右 Margin-->
        <attr name="flMarginLeftAndRight" format="integer" />
        <!--        Labels的上下 Margin-->
        <attr name="flMarginTopAndBottom" format="integer" />
        <!--      Labels 内容上下padding  -->
        <attr name="flPaddingTopAndBottom" format="integer" />
        <!--      Labels 内容左右padding  -->
        <attr name="flPaddingLeftAndRight" format="integer" />
    </declare-styleable>

</resources>

注意:
name:是自定义属性的名字
format:是紫荆一属性数据的格式

2.xml布局中引用属性且配置初始数据


   <com.wkq.flow.FlowLayout
       android:background="@color/teal_200"
       android:id="@+id/fl"
       android:layout_width="wrap_content"
       app:flBackgroundColor="@color/purple_200"
       app:flTextColor="@color/white"
       app:flAngleSize="10"
       app:flPaddingLeftAndRight="40"
       app:flPaddingTopAndBottom="10"
       app:flMarginLeftAndRight="40"
       app:flMarginTopAndBottom="30"
       android:layout_height="wrap_content"/>
  1. 获取自定义属性配置的数据

 var style = context.obtainStyledAttributes(attrs, R.styleable.FlowLayoutStyle)
 
 var bgcolor = style.getColor(  R.styleable.FlowLayoutStyle_flBackgroundColor,context.resources.getColor(R.color.bg_color))
 
 var textColor = style.getColor( R.styleable.FlowLayoutStyle_flTextColor,  context.resources.getColor(R.color.text_color) )
 
 var mLeftAndRightPadding = style.getInt(R.styleable.FlowLayoutStyle_flPaddingLeftAndRight, 10)
 
 var mTopAndBottomPadding = style.getInt(R.styleable.FlowLayoutStyle_flPaddingTopAndBottom, 5)
 
 var leftAndRightMargin = style.getInt(R.styleable.FlowLayoutStyle_flMarginLeftAndRight, 10)
 
 var topAndBottomMargin = style.getInt(R.styleable.FlowLayoutStyle_flMarginTopAndBottom, 5)
 
 var flAngleSize = style.getFloat(R.styleable.FlowLayoutStyle_flAngleSize, 10f)

总结
自定义属性的一些简单属性设置以及获取,方便后期CV

欢迎点赞!!!

相关文章

网友评论

      本文标题:Android 自定义属性

      本文链接:https://www.haomeiwen.com/subject/qatnbrtx.html