标签:
这次只是说明最简单的自定义属性流程
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="test">
<attr name="test" format="string" />
<attr name="testArr" format="integer" />
</declare-styleable>
</resources>
public class MyTextView extends View{
private static final String TAG = "MyTextView";
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);
String text = ta.getString(R.styleable.test_testArr);
int textAttr = ta.getInteger(R.styleable.test_text, -1);
Log.e(TAG, "text:"+text+",textAttr:"+textAttr);
ta.recycle();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:yxm="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.xm.customview.MainActivity">
<org.xm.customview.MyTextView
android:layout_width="100dp"
android:layout_height="200dp"
yxm:testArr="20"
yxm:text="xiaoming" />
</RelativeLayout>
androidstudio中使用:xmlns:yxm="http://schemas.android.com/apk/res-auto"
自动导入命名控件
如果在eclipse中要使用完成的包名,如:xmlns:sdf="http://schemas.android.com/apk/res/org.xm.customview"
给自定义属性添加参数使用制定定义的命名空间,例如: yxm:testArr="20"
public class MyTextView extends View{
private static final String TAG = "MyTextView";
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);
String text = ta.getString(R.styleable.test_text);
int textAttr = ta.getInteger(R.styleable.test_testArr, -1);
Log.e(TAG, "text:"+text+",textAttr:"+textAttr);
ta.recycle();
}
}
R.styleable.test_text
中 text_是自动添加的(必须写),然后添加属性名字text
所以最后会打印:text:xiaoming,textAttr:20, 还是很简单的吧!
标签:
原文地址:http://blog.csdn.net/u013647382/article/details/51336712