Android自定义View&自定义属性

在我们自定义控件过程中通常都需要自定义属性,方便我们配置View的参数。

Android自定义属性可分为以下几步:

自定义属性的声明文件

编写values/attrs.xml,在其中编写styleable和item等标签元素

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="test">
            <attr name="text" format="string" />
            <attr name="testAttr" format="integer" />
        </declare-styleable>
    </resources>

自定义View中获取属性

 //在View的构造方法中通过TypedArray获取
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
String text = ta.getString(R.styleable.test_testAttr);
int textAttr = ta.getInteger(R.styleable.test_text, -1);

在布局中使用

 <com.example.test.MyView
        android:layout_width="120dp"
        android:layout_height="120dp"
        app:testAttr="520"
        app:text="helloworld" />

属性值的类型归纳

  • reference资源id
//属性定义
<attr name = "background" format = "reference" />
//属性使用
<ImageView android:background = "@drawable/图片ID"/>
  • color颜色值
//属性定义
<attr name = "textColor" format = "color" />
//属性使用
<TextView android:textColor = "#00FF00" />
  • boolean布尔值
//属性定义
<attr name = "focusable" format = "boolean" />
//属性使用
<Button android:focusable = "true"/>
  • dimension尺寸值
//属性定义
<attr name = "layout_width" format = "dimension" />
//属性使用
<Button android:layout_width = "42dp"/>
  • float浮点值
//属性定义
<attr name = "fromAlpha" format = "float" />
//属性使用
<alpha android:fromAlpha = "1.0"/>
  • integer整型值
//属性定义
<attr name = "framesCount" format="integer" />
//属性使用
<animated-rotate android:framesCount = "12"/>
  • string字符串
//属性定义
<attr name = "text" format = "string" />
//属性使用
<TextView android:text = "我是文本"/>
  • fraction百分数
//属性定义
<attr name = "pivotX" format = "fraction" />
//属性使用
<rotate android:pivotX = "200%"/>
  • enum枚举
//属性定义
 <attr name="orientation">
        <enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>
//属性使用
<LinearLayout  
    android:orientation = "vertical">
</LinearLayout>
  • flag位或运算
//属性定义
<attr name="gravity">
            <flag name="top" value="0x01" />
            <flag name="bottom" value="0x02" />
            <flag name="left" value="0x04" />
            <flag name="right" value="0x08" />
            <flag name="center_vertical" value="0x16" />
            ...
    </attr>
//属性使用
<TextView android:gravity="bottom|left"/>
  • 混合类型
//属性定义
 <attr name = "background" format = "reference|color" />
//属性使用
<ImageView
android:background = "@drawable/图片ID" />
或者:
<ImageView
android:background = "#00FF00" />
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容