首先我来讲一下为什么要自定义属性。因为我们写了一个自定义控件之后呢,假如里面有一个属性像TextView的text一样,可以根据用户输入什么我们就展示什么内容,那么我们写的自定义控件是不是要获取到用户输入的信息。而信息是通过赋值给属性了,所以我们要写一个自定义的属性。
(1)那就会产生一个问题,那用户输入的信息为什么能跟你的自定义关联起来呢?
因为命名空间将自定义属性跟跟自定义控件相关联起来了。
命名空间:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
这里面的xmlns 全称是xml name Space ,顾名思义是XML的命名空间,而后面的android就是这个空间的名称。
xmlns:android="http://schemas.android.com/apk/res/android
最后面的那个andorid是包名,androidstudio可能让你写成下面这样:
xmlns:yege="http://schemas.android.com/apk/res-auto"
效果也是一样的。
(2)在vlues文件夹下面新建一个资源文件attrs.xml,然后在里面写你要自定义的属性名可类型,比如下面这样:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TestLayout">
<attr name="title" format="string" />
</declare-styleable>
</resources>
我只写了一个自定义属性,然后用户在用的时候,直接写:
xmlns:yege="http://schemas.android.com/apk/res-auto"
<com.example.testadapter.TestLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
yege:title="222" />
yege是我的命名空间名称。我这里只写了一个自定义属性。然后在自定义控件里面去拿到这个属性,已经拿到属性对应的数据展示数来。
(3)在自定义控件中拿到自定义属性,在自定义控件的构造方法里面来获取属性:
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TestLayout);
(4)拿到自定义属性对应的数据:
String string = typedArray.getString(R.styleable.TestLayout_title);
(5)回收typeArray:
typedArray.recycle();