美文网首页
自定义组件之自定义属性

自定义组件之自定义属性

作者: 滴滴滴9527 | 来源:发表于2017-09-08 20:41 被阅读0次

一、组件的属性

我们在布局文件中使用组件时,定义组件的宽、高、背景等属性,这些属性我们并没有特意去定义,它们都是组件的默认属性,在我们sdk安装目录下找到:
sdk\platforms\android-25\data\res\values\attrs.xml.
这里面定义了组件的默认属性,例如View的属性:

.......
<declare-styleable name="View">
        <attr name="id" format="reference" />
        <attr name="background" format="reference|color" />
        <attr name="padding" format="dimension" />
        <attr name="paddingTop" format="dimension" />
        <attr name="paddingBottom" format="dimension" />
        <attr name="paddingStart" format="dimension" />
        <attr name="paddingEnd" format="dimension" />
        <attr name="visibility">
            <enum name="visible" value="0" />
            <enum name="invisible" value="1" />
            <enum name="gone" value="2" />
        </attr>
    .......省略
</declare-styleable>
.......

二、自定义属性

在自定义组件时,我们常常需要自定义属性,自定义属性主要有3个步骤:

1、在res\values\attrs.xml 文件中定义declare-styleable标签,并将自定义的属性都定义在该标签中
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="XView">
        <attr name="attr1" format="string" />
        <attr name="attr2" format="color" />
    </declare-styleable>

</resources>

(1)自定义的属性都放在declare-styleable标签中,该标签的name一般都是自定义组件的名称,此处为XView,也可以取别的名字,但是和自定义组件一个名字通俗易懂.
(2)自定义的属性由2部分组成:属性名name、属性类型format,属性类型一共有下面几种:

boolean:布尔值
color:颜色值
dimension:尺寸,比如dp、sp、px
string:字符串
float:浮点值
integer:整型值

fraction:百分数
一般在动画资源中使用,比如:<scale> 、<rotate>中fromX、fromY就是fraction类型

enum:枚举值
需要在attr标签下使用<enum>标签定义枚举值,例:
        <attr name="sex"  format="enum" >
            <enum name="man" value="0"/>
            <enum name="woman" value="1"/>
        </attr>

flag:位或运算
需要在attr标签下使用<flag>标签定义子标签,像我们常用的gravity、layout_gravity都是该属性类型,例:
        <attr name="my_gravity" format="flag">
            <flag name="left" value="0" />
            <flag name="top" value="1" />
            <flag name="right" value="2" />
            <flag name="bottom" value="3" />
        </attr>

reference:引用另外一个资源
比如android:layout_width="@dimen/activity_horizontal_margin"就是引用另一个尺寸资源


PS:属性可以指定多种类型,比如我们常用的background
    <attr name="background" format="color|reference" />
在布局文件中使用时值为color或者reference都可以:
  android:background="#ff0000ff"
  android:background="@mipmap/ic_launcher"
2、在布局文件中使用自定义属性
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.fgq.demo.XView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:attr1="随风飘扬的Smile"
        app:attr2="#ff0000ff" />

</FrameLayout>

使用自定义属性需要导入命名空间,上面有2个命名空间:

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

第1个是Android本身的,如果没有的话就不能使用组件的默认属性了,第2个是我们自定义属性的.
(1)xmlns后面的android、app是空间名称,我们在设置属性时的前缀就是这个
(2)后面的res/android、res-auto表明属性的出处,前者是android本身的,后者是AndroidStudio里面自定义属性固定的写法.

3、在自定义组件的构造方法中读取属性值
public class XView extends View {

    public XView(Context context) {
        this(context, null);
    }

    public XView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XView);
        String attr1 = a.getString(R.styleable.XView_attr1);
        int attr2 = a.getColor(R.styleable.XView_attr2, 0);
        a.recycle();
    }
}

三、Why

上面写了如何自定义属性、如何使用,但是你肯定疑惑为什么这么写,下面就介绍上面写法的原因.

1、AttributeSet

构造方法中有个参数AttributeSet,之前介绍过,它表示属性集,我们为该组件定义的所有属性都保存在其中,拿上面的XView示例:

public class XView extends View {

    public XView(Context context) {
        this(context, null);
    }

    public XView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            String attributeName = attrs.getAttributeName(i);
            String attributeValue = attrs.getAttributeValue(i);
            Log.d("获取属性", "属性名" + attributeName + "------" + "属性值" + attributeValue);
        }
    }
}

结合Log一看就明白了,AttributeSet 中还有一些其它的方法,感兴趣的可以去看看.

2、TypedArray

(1)获取TypedArray对象
TypedArray是一个数组容器,这个容器中装有Context.obtainStyledAttributes( )方法获取到的属性值.
在获取TypedArray时,一共4个重载方法,我们来看最长的一个:

public final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr,int defStyleRes) 

set:属性集

attrs:我们定义的属性都会在R.java下生成一个id
      在declare-styleable标签下的属性id又会在R.styleable下生成一个int[]类型数组
      数组元素就是declare-styleable标签下所有属性的id
      这里需要的就是这个int[]类型数组

defStyleAttr
defStyleRes
这两个参数涉及到默认theme,一般defStyleAttr传构造方法里面的defStyleAttr,defStyleRes传0就可以了

(2)读取属性值
获取到TypedArray对象之后,我们就可以根据TypedArray一系列getXXX( )方法获取到属性值.比如上面的:

String attr1 = a.getString(R.styleable.XView_attr1);
int attr2 = a.getColor(R.styleable.XView_attr2, 0);

TypedArray中定义了很多getXXX( )方法,XXX是我们定义的属性类型,有些方法有1个参数,有些方法有2个参数,第1个参数是索引值,第2个参数是默认值.

(3)释放资源
使用完TypedArray之后需要调用recycle( )方法释放资源.

3、declare-styleable标签

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="XView">
        <attr name="attr1" format="string" />
        <attr name="attr2" format="color" />
    </declare-styleable>
</resources>
(1)在attrs.xml下所有自定义属性都会在项目的R.java中生成相应的id(R.attr中)
public final class R {
      public static final class attr {
        public static final int attr1=0x7f01013a;
        public static final int attr2=0x7f01013b;
      }
}
(2)如果这些自定义属性时定义在declare-styleable标签下,还会在R.java中生成对应int[]类型数组(R.styleable 中)
public final class R {
      public static final class styleable {
        public static final int[] XView = {
            0x7f01013a, 0x7f01013b
        };
        public static final int XView_attr1 = 0;
        public static final int XView_attr2 = 1;
      }
}
可以看到:R.styleable 中生成了一个int[]类型数组,数组元素就是上面所有自定义属性的id
同时,数组的每个元素都有一个索引XView_attr1 、XView_attr2 
(3)读取在declare-styleable标签下的自定义属性
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XView);
String attr1 = a.getString(R.styleable.XView_attr1);
int attr2 = a.getColor(R.styleable.XView_attr2, 0);

根据int[]类型数组R.styleable.XView获取TypedArray 对象
根据数组元素索引R.styleable.XView_attr1、R.styleable.XView_attr2获取属性值

四、Demo

attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="XView">
        <attr name="text" format="string" />
        <attr name="textSize" format="dimension" />
        <attr name="textColor" format="color" />
    </declare-styleable>

</resources>

布局文件:

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

    <com.fgq.demo.XView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:text="随风飘扬的Smile"
        app:textColor="#ff0000ff"
        app:textSize="16sp" />

</FrameLayout>

XView:

public class XView extends View {

    private static final int DEFAULT_TEXT_COLOR = Color.BLACK;
    private static final int DEFAULT_TEXT_SIZE = 16;

    private String mText;
    private int mTextColor = DEFAULT_TEXT_COLOR;
    private int mTextSize = DEFAULT_TEXT_SIZE;

    private Paint mPaint;

    public XView(Context context) {
        this(context, null);
    }

    public XView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //读取属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XView);
        mText = a.getString(R.styleable.XView_text);
        mTextColor = a.getColor(R.styleable.XView_textColor, DEFAULT_TEXT_COLOR);
        mTextSize = a.getDimensionPixelSize(R.styleable.XView_textSize, DEFAULT_TEXT_SIZE);
        a.recycle();

        initPaint();
    }

    /**
     * 初始化画笔
     */
    private void initPaint() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);
        mPaint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mText, getMeasuredWidth() / 2, getHeight() / 2, mPaint);//绘制文本
    }
}

这里自定义了一个十分简陋的“TextView”,很多东西都没有考虑,不过不要紧,这里主要是让大家明白自定义属性如何定义、使用而已.

相关文章

  • vue2.0组件间传值的方法汇总

    1、组件间的传值 1.1 父组件向子组件传值 子组件自定义一个属性 父组件通过自定义属性绑定值 子组件调用自定义属...

  • vue组件的五种传值方法(父子\兄弟\跨组件)

    一、props/$emit父子组件传值: 父传子 (自定义属性 props) 父组件向子组件传参,通过自定义属性的...

  • vue.js入门之第四篇(自定义组件)

    1、自定义全局组件 2、自定义局部组件 传递数据 [属性] 传递数据(绑定属性) 传递数据(循环) is v-mo...

  • vue3中自定义组件v-model的实现

    主要的两个步骤 自定义组件创建 props属性 modelValue 自定义组件触发update:modelVal...

  • vue的组件通信

    1.父组件向子组件传值 父传子的实现方式:在子组件上使用自定义属性绑定数据,用props声明自定义属性(父组件通过...

  • angular自定义指令相关知识及代码

    大纲 1、自定义指令之——属性指令2、自定义属性指令的运行原理3、自定义属性指令代码实践4、自定义结构指令5、自定...

  • 父子通信 2018-05-29

    父传子 在父组件上自定义一个属性并将想要传到子组件的数据用v-bind绑定到自定义属性上。 在子组件里通过prop...

  • Vue组件通信方法总结

    父传子父组件通过自定义属性给子组件传值,子组件用props接收 子传父父组件在子组件标签上自定义事件,子组件通过$...

  • 3. 自定义控件(3)

    自定义组件之滑动开关

  • Vue父子组件通信

    一、父传子1、可以在父组件上使用自定义属性绑定数据;2、在子组件中需要显示的用props声明自定义属性名,然后就可...

网友评论

      本文标题:自定义组件之自定义属性

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