Android 自定义属性

values新建一个attrs.xml
<resource>
    <declare-styleable name = "MyTextView">
    <attr name="title" format="string"/>
    <attr name="switch_on" format="string"/>
    </declare-styleable>
</resource>

布局文件中

自定义命名空间  res后面接包名

xmlns:exayong="http://schemas.android.com/apk/res/com.exayong.abc"

<MyTextView

exayong:title="hello"

exayong:switch_on="on"

/>

MyTextView.java中 extends RelativeLayout

带属性的构造方法

attrs.getAttributeName(index);

//获取自定义 命名空间,属性的名字

attrs.getAttributeValue(namespace,name);

String myTitle = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.exayong.abc","title");

1 自定义一个View 继承ViewGroup

2 编写组合控件的布局文件,在自定义View中加载 inflate

总结:

把自带的view的某些属性的值 以自定义属性的方式 静态地写在布局文件中,

然后通过自定义view inflate  findviewById -->view 如TextView

通过自定义view带attrs的构造函数中 获取 自定义属性的值

再通过自带的view的方法把这些值设置到自带的view的某些属性中去比如TextView.setText(myTitle);

原文地址:https://www.cnblogs.com/exayong/p/6079307.html