原文地址http://developer.android.com/training/custom-views/create-view.html
说在前面的话:第一次翻译,自知翻译得不是很好,所以请读者(如果有读者的话)不要责怪,我相信以后会做得更好的。
为什么我要去翻译,我想原因有以下几点吧:
- 锻炼我的英语阅读的能力
- 通过认真地翻译,让我可以对翻译的内容有更深入的了解,可以很好的学习其中的知识。
- 将英文翻译为中文,可以帮助其他一些英语阅读有困难的人来学习文中的知识(当然了,我现在能力有限
,翻译的东西都是很简单的,但我希望以后能翻译一些很好的文中)
创建一个View类
- 符合Android标准
- 提供可以在Android XML布局中使用的自定义属性
- 发送可访问的事件(这个翻译得不是很好,纠结中
。。。) - 能够兼容多个Android平台
继承一个View
class PieChart extends View {
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
定义自定义属性
- 在一个<declare-styleable>资源元素中为你的视图自定义属性
- 在xml布局中制定属性的值
- 在运行的时候获取属性的值
- 使用获取到的属性值
<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>
以上代码声明了两个自定义属性,即 showText 和 labelPosition,这两个属性都属于一个名叫PieChart的styleable 实体。按照惯例,这个styleable实体的名字应和自定义view类的类名一样。尽管这不是严格要求你必须要遵循这个惯例,但是许多流行的代买编辑器都依靠这种命名约定来提供代码提示。
<?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>
为了避免必须使用很长的命名空间URI,这个例子中使用了一个 xmlns 的指示符,这个指示符分配了一个别名 custom给命名空间 http://schemas.android.com/apk/res/com.example.customviews ,你可以为你的命名空间取任意的别名。
应用自定义的属性
AttributeSet对象传递到视图类的构造方法中。虽然可以直接从AttributeSet对象中读取value值,但是那样做有一些缺点:
- 属性值的资源引用还没有解决
- 样式没有被应用
AttributeSet 传递给 obtainStyledAttributes() 来代替,这个方法返回一个已经被引用和添加样式的 TypedArray 数组值。
TypedArray 对象中读取属性值。接下来是PieChart类读取它的属性值的例子:
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 对象是一个共享的资源,用完之后要回收(recycle)
添加属性和事件
public boolean isShowText() {
return mShowText;
}
public void setShowText(boolean showText) {
mShowText = showText;
invalidate();
requestLayout();
}
OnCurrentItemChanged的自定义的事件来通知监听者用户已经旋转了饼图从而专注于新的饼图。
为体验设计
- 用android:contentDescription 属性标注你的输入框
- 在适当的时候通过调用
sendAccessibilityEvent()方法来发送可访问的事件 - 支持备用控制器,比如 D-pad 和 trackball
3096



被折叠的 条评论
为什么被折叠?



