您的位置:首页 > 大数据 > 人工智能

自定义属性(styleable,TypeArray,obtainStyledAttributes)

2015-08-28 17:46 357 查看
参考文章:
http://blog.csdn.net/ff313976/article/details/7949614 http://blog.csdn.net/jdsjlzx/article/details/43452927 http://blog.csdn.net/bingospunky/article/details/39890053
如何给自定义控件添加自定义属性呢?

一、创建自定义属性
创建attrs.xml,在其中

<resources>
<declare-styleable name="MyTextView">
<attr name="textSize" format="dimension"></attr>
<attr name="allowTip" format="boolean"></attr>
</declare-styleable>
</resources>
二、创建自定义控件
在com.example.bindservicetest包下创建MyTextView自定义控件,在构造方法中调用下面的方法

void init(Context context, AttributeSet attrs, int defStyle){
Toast.makeText(context, "count="+attrs.getAttributeCount(), Toast.LENGTH_LONG).show();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyle, 0);
this.setTextSize(a.getDimension(R.styleable.MyTextView_textSize, 15));
this.setText(Integer.toString(a.getDimensionPixelOffset(R.styleable.MyTextView_textSize, -5)));
Toast.makeText(context, "allowTip = " + a.getBoolean(R.styleable.MyTextView_allowTip, false), Toast.LENGTH_LONG).show();
a.recycle();
}
三、在布局文件(activity_main.xml)中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:my="http://schemas.android.com/apk/res/com.example.bindservicetest"
.............>
<com.example.bindservicetest.MyTextView

android:id="@+id/mtv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test123"
android:textSize="20sp"
android:gravity="center"
android:textColor="#ff0000"
my:allowTip="true"
my:textSize="30sp"
/>
...........
最后,总结:
一、步骤(共4部)
1.添加自定义属性(styleable的name就是自定义控件名)
2.创建自定义控件
3.在布局文件中添加自定义控件
4.在自定义控件的构造函数(布局文件写的会直接调2个参数context,attrs的构造)中
(1)获取TypeArray对象(即将根据styleable属性索引集合,将传入的第一个参数:属性集合attrs,放入到TypeArray中)
(2)从该对象中获取属性值
typeArray.getDimensionPixelOffset(属性索引名=控件名+属性名,默认值):获取sp、dp
typeArray.getBoolean:获取布尔类型
.........
(3)释放资源:typeArray.recycle();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: