Android自定义属性

作者: 墨革 | 来源:发表于2016-09-21 16:46 被阅读100次

    自定义属性一般包括如下四步:

    1.在values/attrs.xml文件中编写styleable和attr等标签;
    2.自定义一个继承自View的CustomView;
    3.在自定义的CustomView类中通过TypedArray获得属性,并进行相应的操作;
    4.在布局文件中使用自定义的CustomView。

    代码示例

    values/attrs.xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="test">
            <attr name="boundWidth" format="dimension"/>
            <attr name="bound" format="color"/>
        </declare-styleable>
    </resources>
    

    自定义的CustomView类

    public class CustomView extends TextView {
    
        protected float boundWidth;
        protected int boundColor;
        private Paint mPaint;
    
        public CustomView(Context context) {
            super(context);
        }
    
        public CustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);
            boundWidth = ta.getDimension(R.styleable.test_boundWidth,1.0f);
            boundColor = ta.getColor(R.styleable.test_bound, Color.BLACK);
            mPaint = new Paint();
            mPaint.setColor(boundColor);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(boundWidth);
            ta.recycle();
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
            super.onDraw(canvas);
        }
    }
    

    布局文件

    <?xml version="1.0" encoding="utf-8"?>
       <!-- 1.custom名字随意取。
        2.如果是以lib的形式res后面要写绝对路径。-->
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.customattr.CustomView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:padding="8dp"
            android:text="hello"
            custom:boundWidth="8dp"
            custom:bound="#e14949"/>
    </RelativeLayout>
    

    可以看到这是一个继承自TextView的CustomView,TextView本来不带边框,通过自定义给它添加了边框的属性,边框的宽度的属性。

    扩展阅读

    相关文章

      网友评论

        本文标题:Android自定义属性

        本文链接:https://www.haomeiwen.com/subject/wcpaettx.html