XML命名空间

一、概念

XML命名空间提供避免元素命名冲突的方法。

二、常见的XML命名空间

常见的XML命名空间有:android、tools、app(自定义命名空间)。

1.android

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:xml namespace,声明要开始定义一个命名空间。
android:namespace-prefix,命名空间的名字。
http://schemas.android.com/apk/res/android:看起来是一个URL,但是这个地址是不可访问的,实际上这是一个URI(统一资源标识符)。

使用这行代码,我们就可以引用命名空间中的属性,如:


    

在这个布局中,只要以android:开头的属性便是引用了命名空间中的属性,
android是赋予命名空间一个名字,就跟我们平时在定义变量一样,比如我把它取成zwm,那么上面的代码我们也可以写成:


    

2.tools

xmlns:tools="http://schemas.android.com/tools"

(1)tools只作用于开发阶段
当我们切换到视图窗口(Design)中查看时,可以看到tools:开头的属性效果,但是当app被打包时,所有关于tools属性都会被摒弃掉。



    

(2)tools:context开发中查看Activity布局效果
当我们在AndroidManifest.xml中设置一个Activity主题时,主题的效果只能在运行后在Activtiy中显示。如果在布局中使用context属性,就可以在视图窗口(Design)中看到与MainActivity绑定的主题的效果。

tools:context="com.tomorrow.test.MainActivity"

(3)tools:layout开发中查看fragment布局效果
当我们在Activity上加载一个fragment时,需要在运行后才可以看到加载后的效果。如果在布局中使用layout属性,就可以在视图窗口(Design)中看到fragment布局效果。

tools:layout=@layout/yourfragmentlayoutname 

3.app(自定义命名空间)

xmlns:app="http://schemas.android.com/apk/res-auto"(推荐)
或者
xmlns:app="http://schemas.android.com/apk/res/完整的包名"

通常自定义命名空间往往是和自定义View分不开的,当Android自带的控件不能满足需求时,可以自己去绘制一些View,而要为自定义View加上自定义的属性时,就需要创建自定义命名空间。

//attrs.xml


    
       
       
    


//CustomTextView 
public class CustomTextView extends View {
    private int mColor = Color.RED;//默认为红色
    private String mText="I am a Custom TextView";//默认显示该文本
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//画笔
    public CustomTextView(Context context) {
        super(context);
//        init();
    }
    public CustomTextView(Context context, AttributeSet attrs){
        this(context, attrs, 0);//注意不是super(context,attrs,0);
        init();
    }
    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr){//解析自定义属性
        super(context,attrs,defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.CustomTextView);
        mColor = typedArray.getColor(R.styleable.CustomTextView_customColor, Color.RED);
//        如果没有判断,当没有指定该属性而去加载该属性app便会崩溃掉
        if(typedArray.getText(R.styleable.CustomTextView_customText) != null ){
            mText = typedArray.getText(R.styleable.CustomTextView_customText).toString();
        }
        typedArray.recycle();//释放资源
        init();
    }
    private void init(){
        mPaint.setColor(mColor);// 为画笔添加颜色
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mText, 100, 100, mPaint);
    }
}

//main_layout.xml


    

你可能感兴趣的:(XML命名空间)