在编写上面代码时需要注意如下3点:
1. 需要指定命名空间的值。该值将在<LinearLayout>标签的xmlns:mobile属性中定义。
2. 如果在配置组件的属性时指定了命名空间,需要在AttributeSet 接口的相应getter方法中的第1个参数指定命名空间的值,而第2个参数只需指定不带命名空间的属性名即可。
3. TextView类中的onDraw方法一定要在translate方法后面执行,否则系统不会移动TextView中的文本。
下面在main.xml文件中配置了7个IconTextView组件,分别设置了不同的字体大小,同时,文本前面的图像也会随着字体大小的变化而放大或缩小,配置代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <!-- 在下面的标签中通过xmlns:mobile属性定义了一个命名空间 -->
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:mobile="http://net.blogjava.mobile" android:orientation="vertical"
- android:layout_width="fill_parent" android:layout_height="fill_parent">
- <!-- mobile:iconSrc是可选属性,如果未设置该属性,则 IconTextView与TextView的效果相同 -->
- <!-- 由于IconTextView和Main类不在同一个包中,因此,需要显式指定 package -->
- <net.blogjava.mobile.view.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第一个笑脸" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第二个笑脸" android:textSize="24dp" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第三个笑脸" android:textSize="36dp" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第四个笑脸" android:textSize="48dp" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第五个笑脸" android:textSize="36dp" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第六个笑脸" android:textSize="24dp" mobile:iconSrc="@drawable/small" />
- <net.blogjava.mobile.widget.IconTextView
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:text="第七个笑脸" mobile:iconSrc="@drawable/small" />
- </LinearLayout>
复制代码运行本实例后,将显示如图1所示的效果。
附件:
android_4.10.png 注意:虽然很多人认为组件的属性必须以android命名空间开头,该命名空间的值必须是
http://schemas.android.com/apk/res/android。实际上,只是命名空间的值必须是
http://schemas.android.com/apk/res/android而已,命名空间的名称可以是任何值,如下面的代码所示:
- <?xml version="1.0" encoding="utf-8"?>
- <!-- 将android换成了abcd -->
- <LinearLayout xmlns:abcd="http://schemas.android.com/apk/res/android"
- abcd:orientation="vertical" abcd:layout_width="fill_parent"
- abcd:layout_height="fill_parent">
-
- </LinearLayout>
复制代码下一篇:
《Android/OPhone 开发完全讲义》读书笔记(二):Android 中的Activity的生命周期