您的位置:首页 > 移动开发 > Android开发

Android深入了解自定义属性

2017-10-29 17:43 190 查看
Android -- 深入了解自定义属性 http://www.cnblogs.com/wjtaigwh/p/6594680.html  (基础篇)

深入理解Android 自定义attr Style styleable以及其应用 http://www.jianshu.com/p/61b79e7f88fc

Android中View自定义XML属性详解以及R.attr与R.styleable的区别 http://blog.csdn.net/iispring/article/details/50708044

attrs.xml

<declare-styleable name="View">            //在styleable中声明
<attr name="id" format="reference" />
<attr name="background" format="reference|color" />
<attr name="padding" format="dimension" />
<attr name="focusable" format="boolean" />
...
</declare-styleable>

<declare-styleable name="TextView">
<attr name="text" format="string" localization="suggested" />
<attr name="hint" format="string" />
<attr name="textColor" />
</declare-styleable>

<declare-styleable name="ViewGroup_Layout">
<attr name="layout_width" format="dimension">
<enum name="fill_parent" value="-1" />
<enum name="match_parent" value="-1" />
<enum name="wrap_content" value="-2" />
</attr>
</declare-styleable>

<attr name="textSize" format="dimension" />        //也可直接声明,这样定义<attr>属性存在一个问题:不能通过style或theme设置这个属性的值。


format一共支持11种类型

reference, color, boolean,  dimension, string

float, integer, fraction, enum, flag,  混合类型

在java代码中获取的方法

private void init(Context context, AttributeSet attrs, int defStyleAttr) {
       //获取自定义属性的值
       TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView2, defStyleAttr, 0);
       mText = a.getString(R.styleable.MyTextView2_myText);
       mTextColor = a.getColor(R.styleable.MyTextView2_myTextColor, Color.BLACK);
       mTextSize = a.getDimension(R.styleable.MyTextView2_myTextSize, 30f);
       a.recycle();
          ...
       Log.i(TAG, "mText :" + mText + ",mTextColor:" + mTextColor+ ",mTextSize:" + mTextSize);
   }


obtainStyledAttributes函数获取属性

其实我们在前面已经使用了obtainStyledAttributes来获取属性了,现在来看看这个函数的声明吧:

obtainAttributes(AttributeSet set, int[] attrs) //从layout设置的属性集中获取attrs中的属性

obtainStyledAttributes(int[] attrs) //从系统主题中获取attrs中的属性

obtainStyledAttributes(int resId,int[] attrs) //从资源文件定义的style中读取属性

obtainStyledAttributes (AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)//最复杂,请参考原文

一个attr的应用(RecycleView自定义分割线):

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = new int[]{
android.R.attr. listDivider
};
...
}
<!-- Application theme. -->
<style name ="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name= "android:listDivider">@drawable/divider </item >
</style >
<?xml version="1.0" encoding= "utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<!-- 填充的颜色 -->
<solid android:color ="@color/color_red"/>

<!--  线条大小 -->
<size android:height ="1dp" android:width ="1dp"/>
</shape>


 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: