发布在我的网站 http://kesenhoo.github.io/blog/2013/06/30/android-training-ui-creating-custom-views-lesson-1/ ,欢迎访问!

设计良好的类总是相似的。它使用一个好用的接口来封装一个特定的功能,它有效的使用CPU与内存,等等。为了成为一个设计良好的类,自定义的view应该:

  • 遵守Android标准规则。
  • 提供自定义的风格属性值并能够被Android XML Layout所识别。
  • 发出可访问的事件。
  • 能够兼容Android的不同平台。

Android的framework提供了许多基类与XML标签用来帮助你创建一个符合上面要求的View。这节课会介绍如何使用Android framework来创建一个view的核心功能。

Subclass a View

Android framework里面定义的view类都继承自View。你自定义的view也可以直接继承View,或者你可以通过继承既有的一个子类(例如Button)来节约一点时间。

为了允许Android Developer Tools能够识别你的view,你必须至少提供一个constructor,它包含一个Contenx与一个AttributeSet对象作为参数。这个constructor允许layout editor创建并编辑你的view的实例。

1
2
3
4
5
class PieChart extends View {
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
}

Define Custom Attributes

为了添加一个内置的View到你的UI上,你需要通过XML属性来指定它的样式与行为。为了实现自定义的view的行为,你应该:

  • 为你的view在资源标签下定义自设的属性
  • 在你的XML layout中指定属性值
  • 在运行时获取属性值
  • 把获取到的属性值应用在你的view上

为了定义自设的属性,添加 资源到你的项目中。放置于res/values/attrs.xml文件中。下面是一个attrs.xml文件的示例:

1
2
3
4
5
6
7
8
9
<resources>
<declare-styleable name="PieChart">
<attr name="showText" format="boolean" />
<attr name="labelPosition" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
</declare-styleable>
</resources>

上面的代码声明了2个自设的属性,showText与labelPosition,它们都归属于PieChart的项目下的styleable实例。styleable实例的名字,通常与自定义的view名字一致。尽管这并没有严格规定要遵守这个convention,但是许多流行的代码编辑器都依靠这个命名规则来提供statement completion。

一旦你定义了自设的属性,你可以在layout XML文件中使用它们。唯一不同的是你自设的属性是归属于不同的命名空间。不是属于http://schemas.android.com/apk/res/android的命名空间,它们归属于http://schemas.android.com/apk/res/[your package name]。例如,下面演示了如何为PieChart使用上面定义的属性:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
<com.example.customviews.charting.PieChart
custom:showText="true"
custom:labelPosition="left" />
</LinearLayout>

为了避免输入长串的namespace名字,示例上面使用了:custom作为别名,你也可以选择其他的名称所为你的namespace。

请注意,如果你的view是一个inner class,你必须指定这个view的outer class。同样的,如果PieChart有一个inner class叫做PieView。为了使用这个类中自设的属性,你应该使用com.example.customviews.charting.PieChart$PieView.

Apply Custom Attributes

当view从XML layout被创建的时候,在xml标签下的属性值都是从resource下读取出来并传递到view的constructor作为一个AttributeSet参数。尽管可以从AttributeSet中直接读取数值,可是这样做有些弊端(没有看懂下面的两个原因):

  • 拥有属性的资源并没有经过分解
  • Styles并没有运用上

取而代之的是,通过obtainStyledAttributes()来获取属性值。这个方法会传递一个TypedArray对象,它是间接referenced并且styled的。

请看下面的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.PieChart,
0, 0);
try {
mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
} finally {
a.recycle();
}
}

清注意TypedArray对象是一个shared资源,必须被在使用后进行回收。

Add Properties and Events

Attributes是一个强大的控制view的行为与外观的方法,但是他们仅仅能够在view被初始化的时候被读取到。为了提供一个动态的行为,需要暴露出一些合适的getter 与setter方法。下面的代码演示了如何使用这个技巧:

1
2
3
4
5
6
7
8
9
public boolean isShowText() {
return mShowText;
}
public void setShowText(boolean showText) {
mShowText = showText;
invalidate();
requestLayout();
}

请注意,在setShowText方法里面有调用invalidate()) and requestLayout()). 当view的某些内容发生变化的时候,需要调用invalidate来通知系统对这个view进行redraw,当某些元素变化会引起组件大小变化时,需要调用requestLayout方法。

自定义的view也需要能够支持响应事件的监听器。例如,PieChart暴露了一个自设的事件OnCurrentItemChanged来通知监听器,用户已经切换了焦点到一个新的组件上。

我们很容易忘记了暴露属性与事件,特别是当你是这个view的唯一用户时。请花费一些时间来仔细定义你的view的交互。一个好的规则是总是暴露任何属性与事件。

Design For Accessibility

Your custom view should support the widest range of users. This includes users with disabilities that prevent them from seeing or using a touchscreen. To support users with disabilities, you should:

  • Label your input fields using the android:contentDescription attribute
  • Send accessibility events by calling sendAccessibilityEvent() when appropriate.
  • Support alternate controllers, such as D-pad and trackball

For more information on creating accessible views, see Making Applications Accessible in the Android Developers Guide.

【Android Training UI】创建自定义Views(Lesson 1 - 创建一个View类)的更多相关文章

  1. 【Android Training UI】创建自定义Views(Lesson 0 - 章节概览)

    发表在我的独立网站http://kesenhoo.github.io/blog/2013/06/30/android-training-ui-creating-custom-views-lesson- ...

  2. 【Android Training UI】创建自定义Views(Lesson 2 - 自定义Drawing)

    发布在我的网站:http://kesenhoo.github.io/blog/2013/06/30/android-training-ui-creating-custom-views-lesson-2 ...

  3. Android Training - 使用IntentService运行任务(Lesson 1 - 创建IntentService)

    写在http://hukai.me/blog/android-training-18-running-background-service-lesson-1/ 版权声明:本文博客原创文章,博客,未经同 ...

  4. Android开发UI之自定义视图属性

    Android框架中,所有自定义的view类都继承自View,也可以继承Button等view的子类 为了允许ADT能够与view交互,必须提供一个能够获取Context和作为属性的Attribute ...

  5. Android开发UI之自定义动画

    自定义动画,需要新建一个类,继承Animation类. 重写applyTransformation()方法和initialize()方法. applyTransformation(float inte ...

  6. Android Training - 使用IntentService运行任务(Lesson 2 - 发送任务给IntentService)

    写在http://hukai.me/blog/android-training-18-running-background-service-lesson-2/

  7. sharepoint2010 创建自定义列表

    转:http://boke.25k5.com/kan77298.html 如何创建自定义列表 首先了解创建自定义列表中涉及到的几个名词:栏.内容类型. ①栏:栏即列.字段(Field),MSDN中给出 ...

  8. Knockout应用开发指南 第五章:创建自定义绑定

    原文:Knockout应用开发指南 第五章:创建自定义绑定 创建自定义绑定 你可以创建自己的自定义绑定 – 没有必要非要使用内嵌的绑定(像click,value等).你可以你封装复杂的逻辑或行为,自定 ...

  9. (七)Knockout 创建自定义绑定

    创建自定义绑定 你可以创建自己的自定义绑定 – 没有必要非要使用内嵌的绑定(像click,value等).你可以你封装复杂的逻辑或行为,自定义很容易使用和重用的绑定.例如,你可以在form表单里自定义 ...

随机推荐

  1. N-Queens 解答

    Question The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no tw ...

  2. 阿里云主机和RDS使用心得

    本文上非广告,只是将这近1年的使用过程给大家分享一下. 去年下半年,服务器托管到期,加上服务器也使用了5.6年,严重老化,当时正好看到阿里云的宣传广告,就开始了阿里云使用历程.陆续购买了4台云主机,I ...

  3. Android项目打包开启proguard的混淆优化带来的问题

    1.引入一个sdk以后.打包报错: [INFO] Unexpected error while evaluating instruction: [INFO]   Class       = [com/ ...

  4. Android项目实战-云词典

    前段时间在网上看到滴答滴答的一个项目,字典文章,找到一个简单的字.整句翻译功能,词汇,但漫长的岁月项目,二手API数据不再可用,我决定使用其现有的框架来实现其功能,主要采用的技术GSON和Volley ...

  5. php 添加 redis 扩展模块

    由于PHP源码中并未有redis的文件,所以需要自己下载. 下载地址: http://pecl.php.net/get/redis-2.2.5.tgz [root@study package]# ta ...

  6. 在Android Studio中进行单元测试和UI测试

    本篇教程翻译自Google I/O 2015中关于测试的codelab,掌握科学上网的同学请点击这里阅读:Unit and UI Testing in Android Studio.能力有限,如有翻译 ...

  7. CentOS Apache服务器安装与配置

    原文地址:http://www.linuxidc.com/Linux/2014-01/95256.htm 一.安装Apache程序,一般有三种安装方式: Apache在centos下httpd1.直接 ...

  8. ckeditor 使用手册

    CKEditor使用手册 在使用CKEditor过程中遇到了一些问题,现把它整理成手册,以便随时翻阅. 在页面<head>中引入ckeditor核心文件ckeditor.js <sc ...

  9. Apache+tomcat的整合

    http://blog.csdn.net/stefyue/article/details/6918542 为什么要做这个整合呢?当然,首先想到是就是Apache和Tomcat的区别.正因为有区别,有各 ...

  10. Activiti+oracle 启动项目时不能自动建表或更新表的问题分析及解决办法

    现象描述:按照正常配置,第一次启动时不能自动建表 关键配置片段如下: <bean id="processEngineConfiguration" class="or ...