Android Other

View构造方法详解及obtainStyledAttribute

2018-12-27  本文已影响0人  zizi192

构造方法

View的构造方法有如下几个,其中前三个方法是API 1即引入,这也是最常使用的构造方法。但是 View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)是API 21才引入,使用时需要注意兼容性问题。

/**
  * Code中创建View时使用的构造方法
  * Simple constructor to use when creating a view from code.
  */
View(Context context)

/**
  * 绘制Xml中View时使用的构造方法
  * Constructor that is called when inflating a view from XML.
  */
View(Context context,AttributeSet attrs)

/**
  * Perform inflation from XML and apply a class-specific base style from a theme attribute.
  */
View(Context context, AttributeSet attrs, int defStyleAttr)


/**
  * Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource.
  */
 View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

View(Context context, AttributeSet attrs, int defStyleAttr)

日常开发中,使用较多的是前两种构造方法,相信开发者们一定比较熟悉。今天重点要介绍的是第三种构造方法View(Context context, AttributeSet attrs, int defStyleAttr)中的第三个参数defStyleAttr。

参考官方文档的参数详解如下,乍一看无法理解defStyleAttr和defStyleRes的含义,只能看到二者的作用是为View提供一些属性的默认值。

参数详解:
context Context: The Context the view is running in, through which it can access the current theme, resources, etc.
attrs AttributeSet: The attributes of the XML tag that is inflating the view.This value may be null.
defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
defStyleRes int: A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

参考View的实现源码,上述几个参数的作用是传递给context.obtainStyledAttributes来获取TypedArray,进而解析出Attribute。后续开始关键参数的介绍:

public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        this(context);

        final TypedArray a = context.obtainStyledAttributes(
                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);

        <!-- ...snipped for brevity... -->
}
AttributeSet参数

首先来理解XML中Attributes的定义,以ImageView为例:

<ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/icon"
  />

上述XML定义中的layout_width,layout_height和src就组成了AttributeSet对象,但是这些attribute定义是来自于哪里呢?其实系统在attrs.xml中通过<declare-styleable>声明了这些attributes。源码定义如下:

<declare-styleable name="ImageView">
  <!-- Sets a drawable as the content of this ImageView. -->
  <attr name="src" format="reference|color" />

  <!-- ...snipped for brevity... -->

</declare-styleable>

系统针对<declare-styleable>定义在R.java中生成了R.styleable.[name]数组,并对内每个attribute定义了一个R.styleable.[name]_[attribute]常量。上述例子生成的就是R.styleable.ImageView和R.styleable.ImageView_src。

其中R.styleable.[name]是所有attribute资源的数组,通过R.styleable.[name]_[attribute]作为数组的下标来查找指定资源。
在自定义View构造时,开发者经常通过AttributeSet(XML中定义的attributes)+R.styleable.[name](标志哪些attributes需要提取和attribute的排序)可解析后获取TypedArray对象。这是因为AttributeSet直接解析复杂度较大,系统才提供Theme.obtainStyledAttributes获取TypedArray以访问属性。

简单理解,上面的src的处理过程类似下面代码,当然实际源码复杂的多。

public ImageView(Context context, AttributeSet attrs) {
  TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageView, 0, 0);
  Drawable src = ta.getDrawable(R.styleable.ImageView_src);
  setImageDrawable(src);
  ta.recycle();
}
defStyleAttr参数

开发者除了在XML中直接设置View的属性值,eg以上章节中ImageView的src,还可以通过theme来设置属性值。

An attribute in the current theme that contains a reference to a style resource that supplies defaults values for the TypedArray.

再来看一次defStyleAttr的文档说明,书读百遍,其义自现。这次以TextView为例来进行展示。

public TextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.textViewStyle);
    }

参考TextView的构造方法,defStyleAttr入参使用了R.attr.textViewStyle。在系统源码的attrs.xml中找到textViewStyle的定义:

<resources>
  <declare-styleable name="Theme">

    <!-- ...snip... -->

    <!-- Default TextView style. -->
    <attr name="textViewStyle" format="reference" />

    <!-- ...etc... -->

  </declare-styleable>
</resource>

我们使用declare-styleable来定义theme中可使用的attributes。这里指出textViewStyle是一个reference(对资源的引用),在这里应该是对style的引用。

查看源码中的themes.xml中Android的默认主题。开发者可通过对Application或Activity设置theme来使之生效。

<resources>
  <style name="Theme">

    <!-- ...snip... -->

    <item name="textViewStyle">@style/Widget.TextView</item>

    <!-- ...etc... -->

  </style>
</resource>

上述textViewStyle指向的Widget.TextView定义在styles.xml中,有兴趣的同学可以自行查看。

也是通过类似TextView的方法,Android系统为很多原生控件提供了默认属性值。相信大家也可以理解,defStyleAttr参数是当前theme下定义的一个style资源的属性,并为最后生成的TypedArray资源数组提供了默认值的功能。

最后一个参数defStyleRes相对简单一些,是一个style资源的引用来为View提供属性默认值。但是优先级较低。

obtainStyledAttibutes方法中几个参数的优先级如下:

自定义View构造方法实现

在编写自定义View时,一般需要实现至少前两个构造方法。但是如果需要实现所有构造方法,注意不要使用this(...)进行级联调用。推荐的使用方法如下:

public MyView(Context context) {
    super(context);
    init(context, null, 0);
}

public MyView(Context context, AttributeSet attrs) {
    super(context,attrs);
    init(context, attrs, 0);
}

public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context, attrs, defStyle);
}

private void init(Context context, AttributeSet attrs, int defStyle) {
    // do additional work
}

原因是自定义View的父控件可能在构造方法中设置了默认的defStyle。以TextView(Button等也可)的构造方法为例,如果使用this级联调用,而不是super(context),控件就丢失了应用当前theme下R.attr.textViewStyle中定义的默认属性。

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

public TextView(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

public TextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    this(context, attrs, defStyleAttr, 0);
}

公共Attribute定义

一个module的Attribute定义中不能出现同名属性,即使同名属性位于多个attrs.xml文件。这时候可参考系统公共属性的定义,解决方法如下:

<resources>

    <!-- 公共属性 -->
    <attr name="useSkin" format="boolean"/>

    <declare-styleable name="CustomHeaderLoadingLayout">
        <attr name="headerBackground" format="reference"/>
        <attr name="loadingViewType">
            <enum name="colored" value="0"/>
            <enum name="white" value="1"/>
        </attr>
        <attr name="showTip" format="boolean"/>
        <attr name="tipTextColor" format="color|reference"/>
        <attr name="useSkin" />
    </declare-styleable>

    <declare-styleable name="DragBubbleView">
        <attr name="bubbleRadius" format="dimension" />
        <attr name="bubbleColor" format="color" />
        <attr name="bubbleTextPadding" format="dimension" />
        <attr name="bubbleTextSize" format="dimension" />
        <attr name="bubbleTextColor" format="color" />
        <attr name="useSkin"/>
    </declare-styleable>
</resources>

其实只要保证只有一处属性定义语句<attr name="useSkin" format="boolean"/>(也可在某个declare-styleable内定义),可在多个地方进行属性的引用 <attr name="useSkin"/>

参考文档:
https://blog.danlew.net/2016/07/19/a-deep-dive-into-android-view-constructors/
https://stackoverflow.com/questions/9195713/do-i-need-all-three-constructors-for-an-android-custom-view/34301725#34301725
Android 深入理解Android中的自定义属性
Android View构造方法第三参数使用方法详解

上一篇 下一篇

猜你喜欢

热点阅读