android 自定义TextView

TextView 这个控件本身的一些常用属性咱就不具体介绍了,此处仅仅介绍如何自定义一个TextView,最近接触的项目中自定义的东西还挺多的,感觉自定义这个东东还是必须要会的,废话少说,步入正题,先从简单开始吧!!

直接上代码:

1.首先在values/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>


2.自定义一个MyTextView继承TextView

 

package com.test.customviewtest;

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

public class MyTextView extends TextView {
	private String hello = "this is custom_defined";

	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);

		/**
		 * 以下三行若注释掉,那么 activity_main.xml 中的
		 * 
		 * mycustomapp:textColor="#00ff00"
		 * 
		 * mycustomapp:textSize="30px"
		 * 
		 * mycustomapp:title="xml zhong de text"
		 * 
		 * 将不会生效,所以要想xml中的属性值生效,就必须添加如下代码,首先获取TypedArray
		 */

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.MyTextView);
		int textColor = a.getColor(R.styleable.MyTextView_textColor, 0xff969696);
		float textSize = a.getDimension(R.styleable.MyTextView_textSize, 40);
		hello = a.getString(R.styleable.MyTextView_title);

		setText(hello);
		setTextSize(textSize );
		setTextColor(textColor );
		a.recycle();
	}
}


3. layout文件activity_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mycustomapp="http://schemas.android.com/apk/res/com.test.customviewtest"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- 属性:textColor、textSize、title   是attr.xml中定义的 -->

    <com.test.customviewtest.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        mycustomapp:textColor="#00ff00"
        mycustomapp:textSize="30px"
        mycustomapp:title="xml zhong de text" />

</RelativeLayout>



注意这一行代码: xmlns:mycustomapp="http://schemas.android.com/apk/res/com.test.customviewtest"  为命名空间

mycustomapp :自己随意取的名称

http://schemas.android.com/apk/res/  :这一行是固定不变的

com.test.customviewtest    :应用程序的包名

 

经过以上几步,一个简单的自定义就完成了!! 

补充几点:

[1].TypedArray实例是个属性的容器,由 context.obtainStyledAttributes()方法返回得到。AttributeSet是节点的属性集合,在本例中是<com.test.customviewtest.MyTextView 节点中的属性集合!

[2]. 自定义属性的format值,有多种:

  • reference
  • string
  • color
  • dimension
  • boolean
  • integer
  • float
  • fraction
  • enum
  • flag

 

 

 

posted @ 2013-05-02 20:27  行走的思想  阅读(25)  评论(0编辑  收藏  举报  来源