Android xmlns 的作用及其自定义

作者: android 发布时间: 2017-07-04 浏览: 4218 次 编辑

转发请备注原文地址:https://www.niwoxuexi.com/blog/android/article/189.html

有很多人学习Android很长时间了,还不知道xmlns:Android="http://schemas.android.com/apk/res/android 的作用是什么,就知道每个新建xml的时候回自动生成这句话,去掉就会报错


解释:这个是xml的命名空间,有了他,你就可以alt+/作为提示,提示你输入什么,不该输入什么,什么是对的,什么是错的,也可以理解为语法文件。或者语法判断器什么的

这个主要作用是在运行的时候那些控件的属性都是通过它来识别的,如果上面你写错了,不会有任何问题,但是在运行的时候就会有问题,提示你没有指定宽度等什么。这个是不用联网的。

Android 自定义的xmlns其实很简单,语法规则是:

在使用到自定义View的xml布局文件中需要加入

 xmlns:前缀=http://schemas.android.com/apk/res/你的应用程序包路径.

下面用一个小案例说明一下:

如下项目结构图:

说明:自定义了一个MyTextView控件,给MyTextView 添加几个属性,这个时候要是在xml中使用,就要添加命名空间了,这样编译器才能找到相应的属性。

MyTextView.java代码

package com.niwoxuexi.xmlnsdemo;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * Created by niwoxuexi.com on 2017/7/4.
 */
public class MyTextView extends TextView {
    private String mString = "Welcome to www.niwoxuexi.com";
    public MyTextView(Context context) {
        super(context);
    }
    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
        int textColor = a.getColor(R.styleable.MyTextView_textColor, 0XFFFFFF);
        float textSize = a.getDimension(R.styleable.MyTextView_textSize, 36);
        mString = a.getString(R.styleable.MyTextView_title);
        setText(mString);
        setTextSize(textSize);
        setTextColor(textColor);
    }
}

acitivity_main.xml代码:

注意添加的命名控:xmlns:test="http://schemas.android.com/apk/res/com.niwoxuexi.xmlnsdemo"

<?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.niwoxuexi.xmlnsdemo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="欢迎来到-你我学习网"
        android:gravity="center"
        android:layout_marginBottom="40dp"
        android:textSize="16sp"
        android:textColor="#fff"
        android:background="@color/colorPrimary"/>
    <com.niwoxuexi.xmlnsdemo.MyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        test:title="这是自定义的TextView,用来演示xmlns命名空间"
        test:textSize="20px"
        test:textColor="#ff0000"  />
</LinearLayout>

属性文件 value/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">
        <attr name="textColor" format="color"/>
        <attr name="textSize" format="dimension" />
        <attr name="title" format="string"/>
    </declare-styleable>
</resources>

效果图:


最后上代码:https://image.niwoxuexi.com/download/blog/XmlnsDem...