您的位置:首页 > 移动开发 > Android开发

Android中如何使用xmlns

2017-03-16 10:48 197 查看
工作中时常需要自定义控件,除了按键,draw以外,还需要对控件属性进行一些初始化的操作,比如控件的边距,字体大小,颜色等。

本文将根据需求,实现一个自定义的TextView。

1 需求

要求TextView的字体是30sp,颜色是#FF00FFAD。

针对这两个需求,做出如下定义

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="textcolor">#FF00FFAD</color>
</resources>


dimens.xml

<resources>

<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>

<dimen name="text_size">30sp</dimen>

</resources>


2 定义属性声明

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LargeText">
<attr name="textsize" format="dimension" />
<attr name="textcolor" format="color" />
</declare-styleable>
</resources>


这里需要注意的是format属性的定义,format="reference"一般用于字符串,表示引用的是某个string的定义
3 导入控件

有了以上定义,我们就可以在layout文件中加入以上定义的属性了

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:LargeText="http://schemas.android.com/apk/res/com.example.nfctest" //引入自定义属性的风格
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".NFCActivity" >

<com.example.nfctest.LargeText android:id="@+id/state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
LargeText:textsize="@dimen/text_size"     //引用自定义的字体大小
LargeText:textcolor="@color/textcolor" /> //引用自定义的颜色

</RelativeLayout>


引入自定义控件在layout中需要包含packagename,格式是<package-name>.<customize-class_name>

自定义属性风格需要在layout或者view的属性列加载,格式是xmlns:<style-name>=“http://schemas.Android.com/apk/res/<package-name>”

使用自定义属性的格式是<style-name>:<attrs-name>

4 万事俱备,现在需要定义LargeText.java
LargeText.Java

package com.example.nfctest;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;

public class LargeText extends TextView {

public LargeText(Context context) {
this(context, null, 0);
// TODO Auto-generated constructor stub
}

public LargeText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// TODO Auto-generated constructor stub
}

public LargeText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LargeText, defStyle, 0);
int textColor = a.getColor(R.styleable.LargeText_textcolor,
0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.LargeText_textsize, 36);
a.recycle(); //使用类型数组后,需要回收它
setTextSize(textSize);
setTextColor(textColor);
}

}

通过以上4步,自定义的textview就会按照我们定义的属性去显示文字了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: