Android自定义控件

来源:互联网 发布:怎样建立手机淘宝网店 编辑:程序博客网 时间:2024/06/05 05:24
相信在网上已经有无数篇讲解自定义控件的文章,有的讲得挺好的,但是总觉得很多都过于讲原理什么。我觉得对于一个刚接触自定义控件的人来说,他可能想要的是实现自定义控件的一些步骤。简单来说就是一些模版之类的。我也是这样一步步过来的,所以趁着现在有时间,我想把自己的一些总结分享给大家。 自定义 View 涉及到的核心部分有:View 的绘制机制和 Touch 事件传递机制。一,自定义控件步骤 1.创建自定义的 View(1)继承 View 或 View 的子类,添加必要的构造函数(2)定义自定义属性(外观与行为)(3)应用自定义属性:在布局中指定属性值,在初始化时获取并应用到 View 上(4)添加控制属性的方法2.自定义 View 的绘制重写 onDraw()方法,按需求绘制自定义的 view。每次屏幕发生绘制以及动画执行过程中,onDraw 方法都会被调用到,避免在 onDraw 方法里面执行复杂的操作,避免创建对象,比如绘制过程中使用的 Paint,应该在初始化的时候就创建,而不是在 onDraw 方法中。3.使 View 具有交互性一个好的自定义 View 还应该具有交互性,使用户可以感受到 UI 上的微小变化,并且这些变化应该尽可能的和现实世界的物理规律保持一致,更自然。Android 提供一个输入事件模型,帮助你处理用户的输入事件,你可以借助 GestureDetector、Scroller、属性动画等使得过渡更加自然和流畅。二, 自定义控件示例(这里以 CirclePageIndicator 为例)     1. 继承自view,实现构造函数
CirclePageIndicator extends View implements PageIndicator {    public CirclePageIndicator(Context context) {        this(context, null);    }    public CirclePageIndicator(Context context, AttributeSet attrs) {        this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);    }    public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        ...    }}

2,定义属性

<declare-styleable name="CirclePageIndicator">        <!-- Color of the filled circle that represents the current page. -->        <attr name="fillColor" format="color" />        <!-- Color of the filled circles that represents pages. -->        <attr name="pageColor" format="color" />        ... </declare-styleable>

3.应用属性

<!--首先指定命名空间,属性才可以使用--><LinearLayout    xmlns:app="http://schemas.android.com/apk/res-auto"><!--应用属性值-->    <com.viewpagerindicator.CirclePageIndicator        ...        app:fillColor="#FF888888"        app:pageColor="#88FF0000"        /></LinearLayout>

在代码中加载布局中的属性值并应用:

 public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        //加载默认值        final Resources res = getResources();        final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);        //获取并应用属性值        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);        //应用属性值        mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));        ...        a.recycle();//记得及时释放资源    }

4.自定义view的绘制,这一步是可以省略的,根据自己view看需不需要画,绘制无非是位置跟内容,说白了就是需要画什么,在哪画。把握这两方面就可以了。
5,使view可交互
处理了 onTouch 事件,交互更好的自定义控件往往会加一些自然的动画等。

0 0
原创粉丝点击