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资源文件,定义如下:


<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_1attr_2attr_3三个属性,我们在活动布局中这样使用:

 
<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_1attr_2attr_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资源文件,注意文件名称,不要写错了。其中定义如下:


<resources>
    <style name="TestShowStyle">
        "attr_1">这是在style中定义的内容:attr_1
        "attr_2">这是在style中定义的内容:attr_2
        "attr_3">这是在style中定义的内容:attr_3
    style>
resources>

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

<resources xmlns:tools="http://schemas.android.com/tools">
    
    <style name="Theme.Deke" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        
        "colorPrimary">@color/purple_500
        "colorPrimaryVariant">@color/purple_700
        "colorOnPrimary">@color/white
        
        "colorSecondary">@color/teal_200
        "colorSecondaryVariant">@color/teal_700
        "colorOnSecondary">@color/black
        
        "android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant
        
        "testShowThem">@style/testShowInThem
    style>
resources>

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


<resources>
    <style name="TestShowStyle">
        "attr_1">这是在style中定义的内容:attr_1
        "attr_2">这是在style中定义的内容:attr_2
        "attr_3">这是在style中定义的内容:attr_3
    style>
  
    <style name="testShowInThem">
        "attr_1">这是在ThemStyle中引用定义的:attr_1
        "attr_2">这是在ThemStyle中引用定义的:attr_2
        "attr_3">这是在ThemStyle中引用定义的:attr_3
    style>
resources>

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


<resources>
    <style name="TestShowStyle">
        "attr_1">这是在style中定义的内容:attr_1
        "attr_2">这是在style中定义的内容:attr_2
        "attr_3">这是在style中定义的内容:attr_3
    style>

    <style name="testShowInThem">
        "attr_1">这是在ThemStyle中引用定义的:attr_1
        "attr_2">这是在ThemStyle中引用定义的:attr_2
        "attr_3">这是在ThemStyle中引用定义的:attr_3
    style>
  
    <style name="DefaultTestShowStyle">
      "attr_1">这是默认的属性值:attr_1
      "attr_2">这是默认的属性值:attr_2
      "attr_3">这是默认的属性值:attr_3
    style>
resources>

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

<resources xmlns:tools="http://schemas.android.com/tools">
    
    <style name="Theme.Deke" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        
        "colorPrimary">@color/purple_500
        "colorPrimaryVariant">@color/purple_700
        "colorOnPrimary">@color/white
        
        "colorSecondary">@color/teal_200
        "colorSecondaryVariant">@color/teal_700
        "colorOnSecondary">@color/black
        
        "android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant
        
        "testShowThem">@style/testShowInThem
      	"attr_1">这是在系统属性中直接定义的:attr_1
        "attr_2">这是在系统属性中直接定义的:attr_2
        "attr_3">这是在系统属性中直接定义的:attr_3
    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中定义的@style/testShowInThem这一项。而这一项的属性值的取值方式我们在前面已经讲过了。

第三个构造方法:

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里的列表值。defStyleAttrdefStyleRes在前面已经讲过了,在这里不再 赘述。现在所有能提供的和没有提供的都已经放到ats常量里了,怎么使用就直接在里面取就行了。但有几点是要注意的。取String值就用getString方法,用整形的就用getInt方法, 以此类推,不同类型用相应的方法,AS里都有语法提示,这里就不做过多的口水了。

最后,关于验证,就交给你们自己了,这里我只讲一些方法和注意点:
我们在验证defStyleAttrdefStyleRes时,可以先在第四个构造方法中把这两项目传入0即可,这样这两项就不起作用了。

在布局中我们这样做:


<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>
以此为基础,你们逐一验证吧。

Android开发之自定义控件属性篇(Kotlin)_第1张图片

你可能感兴趣的:(android开发,kotlin,android,开发语言)