Android 命名空间跟自定义属性
Android 命名空间和自定义属性
在布局文件中经常看到
这是在申明命名空间,View中要想自己生命的属性有意义,则需要为属性加一个命名空间前缀,如"android"或者"app"。
我们可以定义自己的命名空间来使用自定义属性
步骤:
1 申明命名空间:
这里注意下:
在eclipse中如果要使用你自定义的属性 是不能用res-auto的
必须得替换成你自定义view所属的包(xmlns:myxmlns=""http://schemas.android.com/apk/res/<你的应用程序的包名>"),如果你在恰好使用的自定义属性被做成了lib那就只能使用res-auto了,而在android-studio里,无论你是自己写自定义view还是引用的lib里的自定义的view 都只能使用res-auto这个写法。以前那个包名的写法在android-studio里是被废弃无法使用的。
2 自定义属性
在attrs.xml文件下定义自定义属性
3 在布局文件中使用自定义属性
这里的MyView是一个自定义的view
4 在MyView中得到自定义属性中的值
输出:

关于TypeArray 和 AttributeSet 的用法 推荐参照
http://blog.****.net/lmj623565791/article/details/45022631
在布局文件中经常看到
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
这是在申明命名空间,View中要想自己生命的属性有意义,则需要为属性加一个命名空间前缀,如"android"或者"app"。
我们可以定义自己的命名空间来使用自定义属性
步骤:
1 申明命名空间:
xmlns:zsg="http://schemas.android.com/apk/res-auto"
这里注意下:
在eclipse中如果要使用你自定义的属性 是不能用res-auto的
必须得替换成你自定义view所属的包(xmlns:myxmlns=""http://schemas.android.com/apk/res/<你的应用程序的包名>"),如果你在恰好使用的自定义属性被做成了lib那就只能使用res-auto了,而在android-studio里,无论你是自己写自定义view还是引用的lib里的自定义的view 都只能使用res-auto这个写法。以前那个包名的写法在android-studio里是被废弃无法使用的。
2 自定义属性
在attrs.xml文件下定义自定义属性
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="TestView"> <!--属性名 属性类型--> <attr name="text" format="string" /> <attr name="textColor" format="color" /> </declare-styleable> </resources>
3 在布局文件中使用自定义属性
这里的MyView是一个自定义的view
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zsg="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.zsg.mytextview.MyView android:layout_width="match_parent" android:layout_height="30dp" zsg:text="这是自定义属性" zsg:textColor="#ff0000"/> </RelativeLayout>
4 在MyView中得到自定义属性中的值
public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); //得到TypedArray TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TestView); String text = (String)a.getText(R.styleable.TestView_text); int textColor = a.getColor(R.styleable.TestView_textColor, 0xff000000); Log.d("test", "text:" + text); Log.d("test", "textColor:" + textColor); a.recycle(); } }
输出:
关于TypeArray 和 AttributeSet 的用法 推荐参照
http://blog.****.net/lmj623565791/article/details/45022631