发布在我的网站 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. UESTC_男神的礼物 2015 UESTC Training for Dynamic Programming<Problem A>

    A - 男神的礼物 Time Limit: 3000/3000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit ...

  2. PCRE的安装及使用

    摘自http://www.cnblogs.com/renhao/archive/2011/08/17/2143264.html PCRE的安装及使用 1.主页地址:http://www.pcre.or ...

  3. Unity 角色复活和重新开始游戏

    作者写游戏完成的时候,还需要从新想下如何把游戏设置重新开始,角色如何复活. 一般大多数都会采用这种方式来代替游戏重新开始 Application.LoadLevel("xxx场景" ...

  4. Clash of Clans(COC)资源压缩解密

    Clash of Clans,简称为COC,中文名<部落冲突>,是ios平台上一款相当火爆的战斗策略类游戏,开发商是芬兰的supercell,据说日收入上百万美刀,创造了手游史上的一个神话 ...

  5. MyEclipse 注册码

    MyEclipse 注册码和大家共享一下! 一:MyEclipse_6.0.1GA_E3.3.1_FullStackInstaller注册码 Subscriber:javp Subscription ...

  6. linux系统如何限制远程登录ip

    在Linux系统上限制远程登录的IP,使用系统自带的配置文件. /etc/hosts.allow /etc/hosts.deny 匹配原则  先allow 后deny. 要求: 只允许 192.168 ...

  7. 基于内容的自适应变长编码[CAVLC]

    基于内容自适应的变长编码方式用于编码zigzag顺序扫描的4x4和2x2残差变换系数块. 1.编码系数个数和零序列(coeff_token): coeff_token = <TotalCoeff ...

  8. 完美实现同时分享图片和文字(Intent.ACTION_SEND)

    private void share(String content, Uri uri){ Intent shareIntent = new Intent(Intent.ACTION_SEND); if ...

  9. Android SQLite的使用1(非原创)

    1.继承SQLiteOpenHelper :public class MyOpenHelper extends SQLiteOpenHelper {} 2.重写下面3个方法 package com.e ...

  10. sql server的两个类型转换函数

    今天遇到一个sql的问题,条件中有个去当前月第一天(2013-8-23 0:00:00),很简单CAST(DATEADD(dd,-DAY(GETDATE())+1,GETDATE()) AS DATE ...