在布局文件中经常看到
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.csdn.net/lmj623565791/article/details/45022631
- 大小: 1.6 KB
分享到:
相关推荐
android 自定义view及自定义属性
android 重写控件添加自定义属性,具体可见http://blog.csdn.net/zenmela2011/article/details/42459481
android常常用到自定义属性和自定义控件,本文主要是一个小demo。让你了解如何实现自定义控件和自定义属性的简单写法。
Android如何使用XML自定义属性
Android 自定义view,自定义属性demo
全面详细介绍三种自定义属性方法,结合博客 http://www.cnblogs.com/ldq2016/p/5200365.html 效果更好
虽然Android给我们提供了很多现成的视图控件,但是有时候我们也需要使用到比较复杂的视图组件。这时候基本的控件是无法满足我们的需求的,所以需要进行自定义。例如,我们的app中经常需要header,header中可能有返回...
仿照系统TextView的自定义属性,以及讲解obtainStyledAttributes各个参数的用处,详情请见博客https://blog.csdn.net/qq_29951983/article/details/80219746
自定义android进度条,带有进度指示,项目详情:http://blog.csdn.net/xiaanming/article/details/10298163
android SDK中添加自定义api 对应我的博客http://blog.csdn.net/a624731186 里面android SDK中添加自定义api文章
android自定义流星和自定义顶部导航的使用实例
见博客:http://blog.csdn.net/mybeta/article/details/39962235
Android自定义属性
最近项目中经常需要用到自定义控件,因此自定义属性也是经常要用到的,在此说明一下自定义属性的用法: 自定义属性都存在于/value/attr.xml文件中,以如下格式存在。 代码如下: ”自定义属性名称”> ”属性名称” ...
Android 动画Interpolator和 button自定义涟漪效果和百分比布局
此资源为示例代码,有问题可留言:http://blog.csdn.net/l_wwbs/article/details/53388924
Android自定义Attr属性 的具体使用例子,看完之后,你就知道如何自定义控件的属性
android 自定义属性 简单 实例 好懂
使用自定义属性
NULL 博文链接:https://wangleyiang.iteye.com/blog/1773916