一步一脚印 自定义View 1

自定义View是个让多少Android开发望而怯步的地方,不矫情了。最近准备整理下自定义view。今天从零开始,真正的从零开始。

创建自定义View Class

一个具有良好设计的自定义View就像一个设计良好的Class,它封装了一组有明确功能性的接口,高效的使用CPU和内存资源,因此,为了达到这一目的,自定义View需要:

遵守Android标准
提供Styleable attributes,在XML的布局中使用
提供可访问的接口
可兼容Android多个SDK

Android Framework 提供了多个基础类和xml的tags用来满足不同的需求,本节主要讨论如何用基础的Android Framework来实现具有核心功能的自定义View



继承View

Android framework 中所有V视图类全部继承自View.你自定义的View可以直接继承它或继承已经定义好的view控件,比如Button,TextView.

最最基础的要求是 提供一个带context 和 AttributeSet 为参数的构造器  它允许你的布局编辑器去创建和编辑你的View实例

class PieChart extends View {
    public PieChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}

定义自定义属性(Attributes)

在你的交互页面,添加一个内置的View(如Button),你会通过它的属性标签来控制显示和行为(android:color ,android:onClick) 一个良好设计的View,可以通过xml来设置属性。为了达到这一目的,你应该:

使用<declare-styleable> 标签元素来声明你的属性集合
在XML布局文件中使用
在程序运行时获得该值
在定义View中应用获得的值

本次我们讨论如何自定义属性集合和如何指定使用它们。下节我们学习如何在程序运行时获取和应用这些值。

为了能够自定义属性,使用<declare-styleable>标签元素,你需要在res/values/attrs.xml该目录下创建一个attrs.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>

这段代码声明了2个自定义属性 showText labelPosition  它俩属于名为 PieChart的属性实体.许多有名的Coder都会按着这个命名习惯去做 属性实体名 与 自定义View的名字相同 

一旦你定义了属性,你就可以像内置View的属性一样去使用他们。与之唯一的区别是分属于不同的命名空间,http://schemas.android.com/apk/res/android 是系统内置的命名空间。而自定义的View则为http://schemas.android.com/apk/res/[your package name] 例如,如何使用PieChart属性。

<?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>

为了避免每次使用都要写一个很长的命名空间,我们可以定义并使用别名来代替。比如使用 custom 来代替 http://schemas.android.com/apk/res/com.example.customviews.

你可以任意去定义别名,随便你怎么起。

Notice the name of the XML tag that adds the custom view to the layout. It is the fully qualified name of the custom view class. If your view class is an inner class, you must further qualify it with the name of the view's outer class. further. For instance, the PieChart class has an inner class called PieView. To use the custom attributes from this class, you would use the tag com.example.customviews.charting.PieChart$PieView.












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值