xmlns:android分析 及 自定义xmlns

来源:互联网 发布:淘宝网妈妈装特价 编辑:程序博客网 时间:2024/05/18 00:39

xmlns:android解释

xmlns其实就是xml namespace的缩写,表示使用哪个命名空间。一般布局文件中,都会添加 xmlns:android="http://schemas.android.com/apk/res/android"  ,这就表示告诉开发工具使用android的一些属性。


自定义xmlns

当然也可以自定义一个命名空间,使用自定义的属性。下面通过一个自定义的View的例子来说明。

package com.cb.test;import android.content.Context;import android.content.res.TypedArray;import android.util.AttributeSet;import android.widget.TextView;public class MyView extends TextView {private TypedArray mTypedArray = null;private String mString = null;private int mTextColor = 0;private float mTextSize = 0;public MyView(Context context, AttributeSet attrs) {super(context, attrs);//retrieve attributes from MyView_Attr in attrs.xmlmTypedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView_Attr);//get the values of attributesmTextSize = mTypedArray.getDimension(R.styleable.MyView_Attr_textSize, 36);mTextColor = mTypedArray.getColor(R.styleable.MyView_Attr_textColor,0XFFFFFFFF);mString = mTypedArray.getString(R.styleable.MyView_Attr_title);if (mString == null) {mString = "no title attribute";}setText(mString);setTextSize(mTextSize);setTextColor(mTextColor);mTypedArray.recycle();}}


使用的属性文件在attrs.xml中

<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="http://schemas.android.com/apk/res/android">    <declare-styleable name="MyView_Attr">        <attr name="textColor" format="color" />        <attr name="textSize" format="dimension" />        <attr name="title" format="string" />    </declare-styleable></resources>

最后再在主activity的布局文件中添加自定义的View即可:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:test="http://schemas.android.com/apk/res/com.cb.test"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />    <com.cb.test.MyView        android:layout_width="fill_parent"        android:layout_height="fill_parent"        test:textColor="#efaa0000"        test:textSize="20dp"        test:title="Just do it" /></LinearLayout>

ps:如果自定义的View会用到一些自定义的属性,比如在attrs.xml中定义的,此时就需要加上自定义的命名空间:
 xmlns:test="http://schemas.android.com/apk/res/com.cb.test"

上图:



over,洗洗睡觉了