xmlns:android分析 及 自定义xmlns

本文详细介绍了Android开发中XML命名空间的使用方法,包括标准的android命名空间以及如何定义和使用自定义命名空间来扩展视图属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.xml
		mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView_Attr);
		
		//get the values of attributes
		mTextSize = 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,洗洗睡觉了




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值