Android自定义View

Android自定义View&自定义属性

2022-02-14  本文已影响0人  JianLee

在我们自定义控件过程中通常都需要自定义属性,方便我们配置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" />

属性值的类型归纳

//属性定义
<attr name = "background" format = "reference" />
//属性使用
<ImageView android:background = "@drawable/图片ID"/>
//属性定义
<attr name = "textColor" format = "color" />
//属性使用
<TextView android:textColor = "#00FF00" />
//属性定义
<attr name = "focusable" format = "boolean" />
//属性使用
<Button android:focusable = "true"/>
//属性定义
<attr name = "layout_width" format = "dimension" />
//属性使用
<Button android:layout_width = "42dp"/>
//属性定义
<attr name = "fromAlpha" format = "float" />
//属性使用
<alpha android:fromAlpha = "1.0"/>
//属性定义
<attr name = "framesCount" format="integer" />
//属性使用
<animated-rotate android:framesCount = "12"/>
//属性定义
<attr name = "text" format = "string" />
//属性使用
<TextView android:text = "我是文本"/>
//属性定义
<attr name = "pivotX" format = "fraction" />
//属性使用
<rotate android:pivotX = "200%"/>
//属性定义
 <attr name="orientation">
        <enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>
//属性使用
<LinearLayout  
    android:orientation = "vertical">
</LinearLayout>
//属性定义
<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" />
上一篇 下一篇

猜你喜欢

热点阅读