android仅通过自定义属性id值获取样式自定义属性值

自定义样式属性的使用

自定义样式属性一般是使用在自定义UI控件中,自定义样式属性用来扩展UI控件的样式属性。
使用三步曲如下:
1.声明:自定义样式属性
2.使用:在layout文件使自定义控件时,设置自定义样式属性的值
3.解析:在自定义控件的样式属性解析时,读取自定义样式属性的值

声明自定义样式属性

在values.xml声明CommMyFragmentItem样式属性

<declare-styleable name="CommMyFragmentItem">
    <attr format="reference" name="item_icon"/>
    <attr format="string" name="item_name"/>
    <attr format="string" name="item_daiding"/>
</declare-styleable>

使用自定义样式属性

* com.bank.mysdk.widget.CommMyFragmentItem是自定义UI控件,使用了 CommMyFragmentItem自定义属性 *
如下是一个layout文件中,使用自定义UI控件的同时设置自定义属性值
这里写图片描述
对应的layout文件的排版预览图如下
这里写图片描述

解析自定义样式属性

这里写图片描述

自定义样式属性的ID值数组

每个自定义属性在R文件会对应一个自定义属性ID值数组以及其在每个自定义属性ID值在数组中的索引,如下所示
这里写图片描述
* 注意观察R文件,如下图所示 *
这里写图片描述
自定义属性在资源文件(resources.arsc)的存放关系,如下图所示
这里写图片描述

通过自定义样式属性的ID值获取属性值

通地获取属性ID值获取资源

Resources提供了getIdentifier方法来获取资源id值,即可以不替换R.layout.xxx,R.id.xx的引用。如下为getIdentifier方法的说明

/**
     * Return a resource identifier for the given resource name.  A fully
     * qualified resource name is of the form "package:type/entry".  The first
     * two components (package and type) are optional if defType and
     * defPackage, respectively, are specified here.
     *
     * <p>Note: use of this function is discouraged.  It is much more
     * efficient to retrieve resources by identifier than by name.
     *
     * @param name The name of the desired resource.
     * @param defType Optional default resource type to find, if "type/" is
     *                not included in the name.  Can be null to require an
     *                explicit type.
     * @param defPackage Optional default package to find, if "package:" is
     *                   not included in the name.  Can be null to require an
     *                   explicit package.
     *
     * @return int The associated resource identifier.  Returns 0 if no such
     *         resource was found.  (0 is not a valid resource ID.)
     */
    public int getIdentifier(String name, String defType, String defPackage) {
        return mResourcesImpl.getIdentifier(name, defType, defPackage);
    }

如下为为使用事例

int mViewIdent = this.getResources().getIdentifier("item_fragment_my",
"layout", ContextUtil.getPackageName());
int mIconIdent = this.getResources().getIdentifier("item_fragment_icon",
"id", ContextUtil.getPackageName());
int mNameIdent = this.getResources().getIdentifier("item_fragment_name",
"id", ContextUtil.getPackageName());
int mNextIdent = this.getResources().getIdentifier("item_fragment_next",
"id", ContextUtil.getPackageName());

在解析样式时使用依赖属性ID值

关键逻辑:
1. 分别读取各个属性对应的id值,并构造出自定义属性id值数组(自定义属性id值的数组);
2. 对自定义数组进行排序,这个排序能确保片定义属性id值跟他们在资源文件的排序是一致的,同时还要用于后面的计算属性id值在属性数组的索引(该索引主要用来读取属性值)
3. 计算属性值(id值)在属性id值数组的索引,并获取索引获取属性值(value值)
示例代码如下所示
这里写图片描述

猜你喜欢

转载自blog.csdn.net/SCHOLAR_II/article/details/81666435