obtainStyledAttributes理解

参考:http://www.jianshu.com/p/61b79e7f88fc
在使用

cn.finalteam.rxgalleryfinal 
com.shehabic.droppy

发现样式可在style中配置,
定义如下

/ * @param set The base set of attribute values.  May be null.
* @param attrs The desired attributes to be retrieved.
* @param defStyleAttr An attribute in the current theme that contains a
*   reference to a style resource that supplies
*   defaults values for the TypedArray.  Can be
*   0 to not look for defaults.
* @param defStyleRes A resource identifier of a style resource that
*  supplies default values for the TypedArray,
*  used only if defStyleAttr is 0 or can not be found
*  in the theme.  Can be 0 to not look for defaults.
* /
/ * 
* @param attrs 要解析的那些属性值
* @param set layout的布局配置的
* @param defStyleAttr 通过attr设置
* @param defStyleRes 默认的一个样式
* /
  public final TypedArray obtainStyledAttributes(
            AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr,
            @StyleRes int defStyleRes) {
        return getTheme().obtainStyledAttributes(
            set, attrs, defStyleAttr, defStyleRes);
    }

优先级 set>defStyleAttr>defStyleRes
defStyleAttr示例

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

  <style name="ActivityTheme" parent="Theme.AppCompat.Light">
        <item name="xin_tv_attr">@style/xin_tv_style</item> 
   </style>

 <style name="xin_tv_style">
        <item name="xin_color">#ffff00</item>
        <item name="xin_size">16sp</item>
    </style>

 TypedArray typedArray = obtainStyledAttributes(null, 
    R.styleable.xin_tv, R.attr.xin_tv_attr, R.style.xin_tv2);

1、资源文件定义
declare-styleable 与attr的区别
declare-styleable 相当于attr的集合

2、发现defStyleAttr设置在layout布局文件中不起作用,设置在Activity的theme上或app Theme

3、TypedArray的使用

int color2 = typedArray.getColor(R.styleable.xin_tv_xin_color, Color.BLUE);
 typedArray.recycle();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容