Android-View自定义属性-简化写法

一.声明属性类型(res/values/attrs.xml)


1.自定义属性正式写法,必须有此步骤,属性类型多样(int,float,boolean,enum....)
2.自定义属性简化写法,可忽略此步骤,但属性类型只有字符串

<resources> 
    <declare-styleable name="decAttrs">
        <attr name="name" format="string" />
        <attr name="state" format="boolean" />        
    </declare-styleable>
</resources>

二.使用属性(res/layout/layoutxxx.xml)


<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"

名字空间在Android Studio可用res-auto,而在Eclipse中用http://schemas.android.com/res/apk/包名
    xmlns:myAttr="http://schemas.android.com/apk/res-auto" 

    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.xxx.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

    1.自定义属性正式写法,属性类型多样(int,float,boolean,enum....)
        myAttr:name="abcde"
        myAttr:state="true"

    2.自定义属性简化写法,可忽略步骤一,但属性类型只有字符串
        simpleName="abcde"/>

</RelativeLayout>

三.在java中获取xml属性


public class MyView extends View{

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

        // 1.自定义属性正式写法, 属性类型多样(int,float,boolean,enum....)
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyToggleBtn);     
        int count = ta.getIndexCount();
        for (int i = 0; i < count; i++) {           
            int itemId = ta.getIndex(i);
            switch (itemId) {
            case R.styleable.name:
                name = ta.getString(itemId);                    
                break;
            case R.styleable.state:
                state = ta.getBoolean(itemId, false);               
                break;
            }           
        }

        // 2.自定义属性简化写法, 可忽略步骤一, 属性类型只有字符串
        String testAttrs = attrs.getAttributeValue(null, "simpleName");

    }
}

简书: http://www.jianshu.com/p/b03ef5fab122
CSDN博客: http://blog.csdn.net/qq_32115439/article/details/72670139
GitHub博客:http://lioil.win/2017/05/23/Android_View_attr.html
Coding博客:http://c.lioil.win/2017/05/23/Android_View_attr.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值