在布局文件中经常看到
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. Android文件系统的结构及目录用途、操作方法 整理
  2. Android NDK开发之Android.mk文件
  3. Android studio 3.1.4 无法获取pom文件
  4. android 神奇的android:clipChildren属性
  5. 识别你的手机 Android的属性系统

随机推荐

  1. 记一次新建Android工程报错: Could not do
  2. android 监听系统时区变化,日期变化,时间变
  3. Android中ProgressBar用法简单实例
  4. Android在屏幕任意位置显示对话框
  5. Android上实现zlib解压缩的方法 Inflater
  6. The Android(安卓)ION memory allocator
  7. android 各种常用,不易记的dialog,等控件
  8. android中sqlite的使用
  9. android中限制EditText中输入指定字符
  10. 设置屏幕显示模式ScreenOrientation.