[b]1、在res/values 文件下定义一个attrs.xml 文件.代码如下:[/b]
注意:在xml中,可能不会出现提示,所以需要记住书写格式
属性attr中format的值有一下几种:
"reference" //引用 ,表示用@drawable/ # ffffff等,所以基本上都需要加上这个
"color" //颜色
"boolean" //布尔值
"dimension" //尺寸值
"float" //浮点值
"integer" //整型值
"string" //字符串
"fraction" //百分数,比如200%
可以同时加多个,如:format = "reference|color"
[b]2、创建一个类MyView 集成LinearLayout,必须集成public MyView(Context context,AttributeSet attrs)方法 [/b]
获取里面属性用 名字_ 属性 连接起来就可以.TypedArray 通常最后调用 .recycle() 方法,为了保持以后使用该属性一致性!
[b]3、在布局文件中使用该控件:[/b]
首先一定要加入命名空间:
xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor"
test是自定义的前缀,后面com.android.tutor是项目的包名
如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
注意:在xml中,可能不会出现提示,所以需要记住书写格式
属性attr中format的值有一下几种:
"reference" //引用 ,表示用@drawable/ # ffffff等,所以基本上都需要加上这个
"color" //颜色
"boolean" //布尔值
"dimension" //尺寸值
"float" //浮点值
"integer" //整型值
"string" //字符串
"fraction" //百分数,比如200%
可以同时加多个,如:format = "reference|color"
[b]2、创建一个类MyView 集成LinearLayout,必须集成public MyView(Context context,AttributeSet attrs)方法 [/b]
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.mys);
View titleView = LayoutInflater.from(context).inflate(R.layout.head, null);
addView(titleView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mIcon = (ImageView)titleView.findViewById(R.id.icon);
mTitle = (TextView)titleView.findViewById(R.id.title);
mIcon.setBackgroundResource(array.getResourceId(R.styleable.mys_icon, -1));
mTitle.setText(array.getString(R.styleable.mys_title));
获取里面属性用 名字_ 属性 连接起来就可以.TypedArray 通常最后调用 .recycle() 方法,为了保持以后使用该属性一致性!
[b]3、在布局文件中使用该控件:[/b]
首先一定要加入命名空间:
xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor"
test是自定义的前缀,后面com.android.tutor是项目的包名
如:
<com.example.test.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
test:icon="@drawable/nearby_4"
test:title="this is title"
/>