Android开发之自定义控件(Kotlin篇)

以前在用Java开发的时候就想写个教程,心想在自己头上的阵地还没完全失守之前,总得给后来者传授点经验,装逼也好有个范儿不是,有点光总得散一散吧。可是这年诸事不顺,又来个疫情,就搁下了。这一年多毛钱都没挣到,家里家外的也不招待见,在工作室没事就瞎捣鼓,人都走光了,就剩光杆司令一人了,就学了些Kotlin,把目前的一个项目转战到Kotlin阵地了。这玩意不用不知道,一用就丢不掉,比Java好用太多了。很是丝滑啊。这不,年底了闲着也是闲着,想着用Kotlin把之前的想法走一遍。写的不好之外大家多指点。

 

系统提供的东西难免有不顺手的时候,那么我们自己写控件应该怎么写呢。动手之前有些知识总得搞清楚才行,这样造起来才得劲。

所有控件都是继承View的,我们创建一个类,继承View, 取名TestShow, 我们都知道,父View有四个构造方法,如下所示:


class TestShow: View {

val TAG:String = "TestShow";

constructor(context: Context): this(context, null)

constructor(context: Context, attrs: AttributeSet?): this(context, attrs, R.attr.testShowStyleThem)

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, R.style.DefaultTestShowStyle)

constructor(context: Context, attrs:AttributeSet?, defStyleAttr: Int, defStyleRes: Int): super(context, attrs, defStyleAttr, defStyleRes)

}

当我们用代码构建控件实例的时候,会调用第一个构造方法;当我们在布局文件构建控件的时候,会调用第二个构造方法;第三个和第四个构造方法是人为调用的,系统不会主动调用。上面的代码中,前三个构造方法中我们用了`this`关键字来委托构建的,只有最后一个调用了父类的方法。这个控件构造时其实是一个链式调用关系,不管是代码构建,还是布局构建,最终都会调用第四个构造方法。其上面的构造方法中的几个参数说明如下:

  •  context: Context 执行环境的上下文,什么是上下文呢,说白了就是一个执行主体,类似一个对象主体、闭包主体等。
  • attrs: AttributeSet 属性集,就是在资源文件attrs.xml中定义的属性集,我们在布局中写的控件属性就包含在这个里面。
  • defStyleAttr: Int 默认的样式属性
  • defStyleRes: Int 所有自定义属性默认值

可以看到,同一个属性可以从多个地方获取到值,那么,同一种情况下,最终的值是从哪里来的呢。其实,属性值的获取有个顺序或者说优先级,由高到低如下所示:

  1.  代码中直接设置的值
  2.  AttributeSet中的值,即布局构建方式中的属性;
  3.  布局中用style指定的属性值;
  4.  defStyleAttr中设置的;
  5. defStyleRes中设置的;
  6. 在Theme中直接设置的属性。

 

那么到具体的应用上该怎么使用呢?我们以上面的代码示例为基础,在项目的资源目录的`res\values\`目录下创建`attrs.xml`资源文件,定义如下:

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

<resources>

<declare-styleable name="TestShow">

<attr name="attr_1" format="string" />

<attr name="attr_2" format="string" />

<attr name="attr_3" format="string" />

</declare-styleable>



<attr name="testShowThem" format="reference" />

</resources>

上面我们用`declare-styleable`定义了一个属性列表,我们给这个属性列表取了个名字叫`TestShow`, 没错,就是我们自己控件的名字,这个名字是随意的,但我们建议用控件名。这个里面列出了我们自定义控件的自定义属性,即要对外暴露的属性。属性以`attr`定义, `name`为属性名, `format`为取值类型,共有以下这么几类:

 

  • - boolean: 布尔型,表示attr取值为true或者false
  • - color: 颜色类型,例如#ff33f6,或者是一个指向color的资源id,例如`R.color.colorAccent`.
  • - dimension: 尺寸类型,例如例如取值14sp、16dp等,也可以是一个指向dimen的资源id,例如`R.dimen.dp_16`
  • - float: 浮点型
  • - fraction: 百分数类型,只能以%结尾,例如30%
  • - integer: 整型
  • - string: String类型,或者一个指向String的资源id,例如`R.string.testString`
  • - reference: 引用类型,如 `R.drawable.id`
  • - enum: 枚举类型。
  • - flag: flag类型,用于位运算。

**注意**

attr节点有两种子节点,enum和flag,enum和flag不能混合使用。

enum可以用format声明,也可以不声明,其值只能是int类型,且只能有一个值。意思就是说我们在布局中为enum类型只能赋于int类型的值。

flag不可以format声明,value也只能是int,但是可以利用|设置多个值。例如下面的定义:

<declare-styleable name="CustomView">

<attr name="color" format="color|reference"/>

<attr name="font" format="dimension"/>

<attr name="text" format="string"/>

<attr name="type" format="enum">

<enum name="enum1" value="1"/>

<enum name="enum2" value="2"/>

</attr>

<attr name="flag">

<flag name="flag1" value="0x01"/>

<flag name="flag2" value="0x02"/>

</attr>

</declare-styleable>

现在基本属性定义我们已经会了,要用到几个属性或是说要暴露几个属性,我们就在这里定义几个属性。还是以前面`TestShow`定义的为例,我们在定义了`attr_1`、 `attr_2`、`attr_3`三个属性,我们在活动布局中这样使用:

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

<androidx.constraintlayout.widget.ConstraintLayout

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

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<udf.component.TestShow

android:layout_width="match_parent"

android:layout_height="match_parent"

app:attr_1="这是布局中直接赋值的:attr_1"

app:attr_2="这是布局中直接赋值的:attr_2"

app:attr_3="这是布局中直接赋值的:attr_3"

style="@style/TestShowStyle">

</udf.component.TestShow>

</androidx.constraintlayout.widget.ConstraintLayout>

关于命名空间的问题,这里简短说明一下, 上面以`xmlns`开头的就是命名空间,为了区分系统属性及其它第三方控件属性,我们自定义的控件总是要用到我们自己的命名空间,一般我们以`xmlns:名称="http://schemas.android.com/apk/res-auto"`来命名我们自定义的属性, 这里的名称我们用`app`来命名,那么,上面`udf.component.TestShow`控件中以app开头的属性就是我们自定义的属性,其赋值要符合我们前面定义的规则,前面我们为`attr_1`、 `attr_2`、 `attr_3`定义的的类型为:`string`类型,所以我们这里只能用字符串类型赋值。

app:attr_1="这是布局中直接赋值的:attr_1"

app:attr_2="这是布局中直接赋值的:attr_2"

app:attr_3="这是布局中直接赋值的:attr_3"

前面还有个`style="@style/TestShowStyle"`的定义,表示当我们没有在布局中显式的为三个属性赋值,那么就用这个`style`里的值。可这个值在哪儿呢。其实已经很清楚了,就是在`@style/TestShowStyle`中, 用@表示我们要引用系统资源文件中的定义属性。这个资源文件类型叫`style`,接下来,我们来定义为个引用类型。

前面我们在资源目录中增加了`attrs.xml`资源文件,我们在项目的资源目录的`res\values\`目录下创建`styles.xml`资源文件,注意文件名称,不要写错了。其中定义如下:

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

<resources>

<style name="TestShowStyle">

<item name="attr_1">这是在style中定义的内容:attr_1</item>

<item name="attr_2">这是在style中定义的内容:attr_2</item>

<item name="attr_3">这是在style中定义的内容:attr_3</item>

</style>

</resources>

我们在前面已经定义了属性的类型,这里只是引用属性值,所以这里的值也是string类型的。这样说应该很清楚了吧。这样以来,当我们没有在布局中直接为属性赋值,但只要写了style引用,那么,我们的属性就会从style引用的资源里找值了。也许你会问,我们要是也没有写style引用语句,属性值从哪儿来呢,对,这就是样式值。当我们使用系统控件时,即使我们啥都不写,我们的系统控件也有着色和大小等。那我们的自定义属性可不可以也能做到这样呢,答案是肯定的。当然,系统不会知道我们自定义的属性是什么,哪儿有值哪儿没有值,这些我们得告诉系统,说的再明白一点就是按照前面说的那个优先级顺序定义就行了。还记得我们在`attrs.xml`中定义属性时,特意单独定义了一个属性吗:`<attr name="testShowThem" format="reference" />`,伏笔当然是有意义的。这就是我们要说的优先级当中的第四项:`defStyleAttr`, 我们打开系统资源文件下的`themes.xml`, 这里面记录了系统样式的一些属性定义,

<resources xmlns:tools="http://schemas.android.com/tools">

<!-- Base application theme. -->

<style name="Theme.Deke" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

<!-- Primary brand color. -->

<item name="colorPrimary">@color/purple_500</item>

<item name="colorPrimaryVariant">@color/purple_700</item>

<item name="colorOnPrimary">@color/white</item>

<!-- Secondary brand color. -->

<item name="colorSecondary">@color/teal_200</item>

<item name="colorSecondaryVariant">@color/teal_700</item>

<item name="colorOnSecondary">@color/black</item>

<!-- Status bar color. -->

<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>

<!-- Customize your theme here. -->

<item name="testShowThem">@style/testShowInThem</item>

</style>

</resources>

我们在当前系统样式的后面添加`<item name="testShowThem">@style/testShowInThem</item>`, 这样,当我们在布局中即没有直接指定属性值以及也没有指定style值的时候,就会在这里找这个值,系统为什么会找这个值呢,一会后面我们讲构造方法的时候具体再说,现在可以看到,我们在前面定义这个属性的时候类型定义为`format="reference"`,是一个引用类型,所以我们这里要引用一个Style, 此处我们引用了一个名为`testShowInThem`的样式属性集,那我们就来看看这个样式吧,这个样式可以直接在`themes.xml`里定义,也可以在`styles.xml`里定义,不过我建议在`styles.xml`里定义。如下所示:

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

<resources>

<style name="TestShowStyle">

<item name="attr_1">这是在style中定义的内容:attr_1</item>

<item name="attr_2">这是在style中定义的内容:attr_2</item>

<item name="attr_3">这是在style中定义的内容:attr_3</item>

</style>

<style name="testShowInThem">

<item name="attr_1">这是在ThemStyle中引用定义的:attr_1</item>

<item name="attr_2">这是在ThemStyle中引用定义的:attr_2</item>

<item name="attr_3">这是在ThemStyle中引用定义的:attr_3</item>

</style>

</resources>

这样就完整了。不过还没完,前面说的的取值优先列表中的第5项还有个`defStyleRes`,是个什么意思呢,其实就是一个默认值,也就是说,上面4项取值都失败的情况下,就会以这个定义为默认值,这时说的失败就是要么没找到,要么我们人为给关闭了,而不是程序出错的意思。从这个名字我们就能认识到它也是一个style, 我们只需定义一个默认的style,在构造方法里指定一下就OK了。如下如示,我们在styles.xml里再定义一个样式属性集:

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

<resources>

<style name="TestShowStyle">

<item name="attr_1">这是在style中定义的内容:attr_1</item>

<item name="attr_2">这是在style中定义的内容:attr_2</item>

<item name="attr_3">这是在style中定义的内容:attr_3</item>

</style>



<style name="testShowInThem">

<item name="attr_1">这是在ThemStyle中引用定义的:attr_1</item>

<item name="attr_2">这是在ThemStyle中引用定义的:attr_2</item>

<item name="attr_3">这是在ThemStyle中引用定义的:attr_3</item>

</style>

<style name="DefaultTestShowStyle">

<item name="attr_1">这是默认的属性值:attr_1</item>

<item name="attr_2">这是默认的属性值:attr_2</item>

<item name="attr_3">这是默认的属性值:attr_3</item>

</style>

</resources>

我们定义了一个`DefaultTestShowStyle`的样式,这样优先级的前5项我们就已经搞定了,那最后一项`在Theme中直接设置的属性`是什么意思呢,顾名思义就是直接在系统样式里直接定义的, 我们在Themes.xml文件中的系统属性后面添加属性如下:

<resources xmlns:tools="http://schemas.android.com/tools">

<!-- Base application theme. -->

<style name="Theme.Deke" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

<!-- Primary brand color. -->

<item name="colorPrimary">@color/purple_500</item>

<item name="colorPrimaryVariant">@color/purple_700</item>

<item name="colorOnPrimary">@color/white</item>

<!-- Secondary brand color. -->

<item name="colorSecondary">@color/teal_200</item>

<item name="colorSecondaryVariant">@color/teal_700</item>

<item name="colorOnSecondary">@color/black</item>

<!-- Status bar color. -->

<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>

<!-- Customize your theme here. -->

<item name="testShowThem">@style/testShowInThem</item>

<item name="attr_1">这是在系统属性中直接定义的:attr_1</item>

<item name="attr_2">这是在系统属性中直接定义的:attr_2</item>

<item name="attr_3">这是在系统属性中直接定义的:attr_3</item>

</style>

</resources>

至此,我们属性定义部分已经全部完成了,那么,如何让我们自定义的控件和我们定义的这些属性关联呢,那就是我们前面说的4个构造方法了。让我们重新回到构造方法的话题。

class TestShow: View {

val TAG:String = "TestShow";

constructor(context: Context): this(context, null)

constructor(context: Context, attrs: AttributeSet?): this(context, attrs, R.attr.testShowThem)

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, R.style.DefaultTestShowStyle)

constructor(context: Context, attrs:AttributeSet?, defStyleAttr: Int, defStyleRes: Int): super(context, attrs, defStyleAttr, defStyleRes){

val ats = context.obtainStyledAttributes(attrs,R.styleable.TestShow, defStyleAttr,defStyleRes)

val attr1: String? = ats.getString(R.styleable.TestShow_attr_1)

val attr2: String? = ats.getString(R.styleable.TestShow_attr_2)

val attr3: String? = ats.getString(R.styleable.TestShow_attr_3)



Log.i(TAG, "Attr_1:$attr1")

Log.i(TAG, "Attr_2:$attr2")

Log.i(TAG, "Attr_3:$attr3")

}

}

> 第一个构造方法

> `constructor(context: Context): this(context, null)`

> 是用于我们用代码的方式使用的,没有什么可说的,即:

val testShow = TestShow(this)

它的委托方式中调用了第2个构造方法,有两个参数,第一个是上下文,第二个为null, 所以属性只能在程序中用代码指定。

第二个构造方法,

`constructor(context: Context, attrs: AttributeSet?): this(context, attrs, R.attr.testShowThem)`

> 是我们在布局文件中构造控件的方式用的。其中的`attrs`就是我们在布局文件中指定的属性集(在布局文件中直接指定的属性或通过Style引用指定的属性)。布局中指定了就有,没有指定就没有。委托方法中调用了第三个构造方法,其中参数`R.attr.testShowThem`,(当我们在`attrs.xml`中定义的属性最终都会在系统资源文件R中自动生成,我们不用人功干预。)通过名字我们就知道这个就是我们在`attrs.xml`中定义的`<item name="testShowThem">@style/testShowInThem</item>`这一项。而这一项的属性值的取值方式我们在前面已经讲过了。

 

 第三个构造方法:

`constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, R.style.DefaultTestShowStyle)`

> 又调用了第四个构造方法, 前三个参数很明确了,第四个参数我们传入了一个资源文件`R.style.DefaultTestShowStyle`, 你是不是有种豁然开朗的感觉了。这个就是我们前面设置的默认值的定义,在styles.xml里定义的。

 重点是我们的第四个构造方法:

 `constructor(context: Context, attrs:AttributeSet?, defStyleAttr: Int, defStyleRes: Int): super(context, attrs, defStyleAttr, defStyleRes){

 val ats = context.obtainStyledAttributes(attrs,R.styleable.TestShow, defStyleAttr,defStyleRes)`

> 不管是哪种方式,最终都会调用到最后一个次构造方法,既然相当的属性文件都传进来了,那值怎么取呢,看下面:

`val ats = context.obtainStyledAttributes(attrs,R.styleable.TestShow, defStyleAttr,defStyleRes)`

 

所有的值按照前面的讲的取值优先级规则通过这个方法获取到。这个方法中的`R.styleable.TestShow`是不是有点熟悉,就是我们在 `attrs.xml`中通过 `declare-styleable`语法定义的属性集。也就是最终复合到attrs里的列表值。`defStyleAttr`和`defStyleRes`在前面已经讲过了,在这里不再 赘述。现在所有能提供的和没有提供的都已经放到`ats`常量里了,怎么使用就直接在里面取就行了。但有几点是要注意的。取String值就用`getString`方法,用整形的就用`getInt`方法, 以此类推,不同类型用相应的方法,AS里都有语法提示,这里就不做过多的口水了。

 

#### 最后,关于验证,就交给你们自己了,这里我只讲一些方法和注意点:

#### 我们在验证`defStyleAttr`和`defStyleRes`时,可以先在第四个构造方法中把这两项目传入0即可,这样这两项就不起作用了。

在布局中我们这样做:

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

<androidx.constraintlayout.widget.ConstraintLayout

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

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">


<udf.component.TestShow

android:layout_width="match_parent"

android:layout_height="match_parent"

app:attr_1="这是布局中直接赋值的:attr_1"

app:attr_2="这是布局中直接赋值的:attr_2"

app:attr_3="这是布局中直接赋值的:attr_3"

style="@style/TestShowStyle">

</udf.component.TestShow>


<udf.component.TestShow

android:layout_width="match_parent"

android:layout_height="match_parent"

style="@style/TestShowStyle">

</udf.component.TestShow>


<udf.component.TestShow

android:layout_width="match_parent"

android:layout_height="match_parent">

</udf.component.TestShow>


</androidx.constraintlayout.widget.ConstraintLayout>

 

#### 以此为基础,你们逐一验证吧。

上一篇:一直滚动的TextView[跑马灯效果]


下一篇:python实训day8