Android自定义布局属性

Android自定义布局属性

自定义属性的步骤

1.自定义xml文件
2.布局中使用
3.代码中使用

1.自定义xml文件

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

</resources>

常见的format

reference:引用资源

string:字符串

Color:颜色

boolean:布尔值

dimension:尺寸值

float:浮点型

integer:整型

fraction:百分数

enum:枚举类型

flag:位或运算


举个例子:

 <declare-styleable name="PercentView">
        <attr name="percent_circle_gravity"><!--圆形绘制的位置-->
            <flag name="left" value="0" />
            <flag name="top" value="1" />
            <flag name="center" value="2" />
            <flag name="right" value="3" />
            <flag name="bottom" value="4" />
        </attr>
        <attr name="percent_circle_radius" format="dimension" /><!--圆形半径-->
        <attr name="percent_circle_progress" format="integer" /><!--当前进度值-->
        <attr name="percent_progress_color" format="color" /><!--进度显示颜色-->
        <attr name="percent_background_color" format="color" /><!--圆形背景色-->
    </declare-styleable>

2.在布局中使用

要声明命名空间


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:joy="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.whoislcj.views.PercentView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_margin="10dp"
        android:background="@color/red"
        android:padding="10dp"
        joy:percent_background_color="@color/gray"
        joy:percent_circle_gravity="left"
        joy:percent_circle_progress="30"
        joy:percent_circle_radius="50dp"
        joy:percent_progress_color="@color/blue" />

</LinearLayout>

3.代码中使用


public class MyTextView extends View {

    private static final String TAG = MyTextView.class.getSimpleName();

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        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);

        Log.e(TAG, "text = " + text + " , textAttr = " + textAttr);

        ta.recycle();
    }

}

参考:
http://www.cnblogs.com/whoislcj/p/5711001.html
http://blog.csdn.net/lmj623565791/article/details/45022631/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值