Android自定义布局属性

来源:互联网 发布:换手率短线炒股软件 编辑:程序博客网 时间:2024/06/01 09:16
需要在values下定义attrs.xml


<declare-styleable name="myStyleable">
        <attr name="max" format="integer"/>
        <attr name="progress" format="integer"/>
        <attr name="textSize" format="dimension"/>
        <attr name="smallBgColor" format="color"/>
        <attr name="progressColor" format="color"/>
    </declare-styleable>
其中fomat表示属性的取值类型


integer:整数
dimension:尺寸 dp dip sp px
color:颜色
string:字符串
float:浮点数 android:rating="1.5"
referrence:引用 @id/btn @drawable/pic
解析属性


public XykjProgressBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //解析自定义属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.myStyleable);
        textSize = ta.getDimensionPixelSize(R.styleable.myStyleable_textSize, 0);
        max = ta.getInteger(R.styleable.myStyleable_max,100);
        progress = ta.getInteger(R.styleable.myStyleable_progress,0);
        smallBgColor = ta.getColor(R.styleable.myStyleable_smallBgColor,0xff3F51B5);
        progressColor = ta.getColor(R.styleable.myStyleable_progressColor,0xffFF4081);
        //释放资源
        ta.recycle();
    }
使用属性


需要在布局中声明前缀的命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"


<com.xykj.myprogressbar.XykjProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:textSize="30sp"
        app:smallBgColor="#ff000000"/>
原创粉丝点击