Android自定义属性:attr.xml 与 TypedArray

时间:2014-05-08 23:01:34   收藏:0   阅读:453

1.attr.xml

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>
bubuko.com,布布扣

 

2.在构造方法中使用

bubuko.com,布布扣
public MyView(Context context,AttributeSet attrs){
        super(context,attrs);
        mPaint = new Paint();
        
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        
        int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);     //怎么获取:名字_ 属性 连接起来就可以
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
        
        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        
        a.recycle();
    }
bubuko.com,布布扣

 

3.在布局文件中使用

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"            
    xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"                 //自定义属性前缀 与 包名
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

<com.android.tutor.MyView
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    test:textSize="20px"
    test:textColor="#fff"/>
</LinearLayout>
bubuko.com,布布扣

 

 

Android自定义属性:attr.xml 与 TypedArray,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!