Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定义控件开发完全指南

編輯:關於 Android 開發

Android 自定义控件开发完全指南

开发自定义控件的步骤:

1、了解 View 的工作原理;2、编写继承自 View 的子类;3、为自定义 View 类增加属性;4、绘制控件;5、响应用户消息;6、自定义回调函数。

一、View 结构原理

Android 系统的视图结构设计也采用了组合模式:View 作为所有图形的基类,ViewGroup 对 View 继承扩展为视图容器类。

View 定义了绘图的基本操作,由三个函数完成:measure()、layout()、draw(),其内部又分别包含 onMeasure()、onLayout()、onDraw() 三个子方法。

1、measure 操作主要用于计算视图的大小,即宽度和长度。在 View 中定义为 final 类型,子类不能修改。measure() 会调用 onMeasure(),视图大小的最终确定就在这里。measure 只是对 onMeasure 的包装,子类可以覆写 onMeasure() 实现自己的计算方式,并通过 setMeasuredDimension(width, height) 保存结果。

2、layout 操作用于设置视图在屏幕中显示的位置,同样定义为 final 类型。layout() 有两个基本操作:setFrame(l, t, r, b) 保存子视图在父视图中的具体位置;onLayout() 在 View 中什么都不做,主要供 ViewGroup 类型布局子视图使用。

3、draw 操作利用前两步得到的参数将视图显示在屏幕上,子类也不应修改。其内部定义了绘图的基本流程:绘制背景;若需显示渐变框则做准备工作;调用 onDraw() 绘制视图本身;调用 dispatchDraw() 绘制子视图;按需绘制渐变框;绘制滚动条。

从上面可以看出,自定义 View 至少需要覆写 onMeasure() 和 onDraw() 两个方法。

二、View 类的构造方法与创建方式

创建自定义控件有三种主要方式:

1)继承已有的控件来实现:当目标控件与已有控件在很多方面类似时,通过扩展现有控件满足要求。

2)继承一个布局文件来实现:做组合控件时常用。此时不用 onDraw 方法,在构造方法中通过 inflater 加载自定义控件的布局文件,再 addView(view),图形界面就加载进来了。

3)继承 View 类来实现:使用 GDI 绘制出组件界面,一般在前两种方式无法实现时使用。

三、为自定义 View 增加属性的两种方法

1)在 View 类中定义。通过构造函数引入的 AttributeSet 去查找 XML 布局的属性名称,再找到它对应引用的资源 ID 去取值。

案例:实现一个带文字的图片(图片、文字通过 onDraw 重绘实现)

public class MyView extends View {
    private String mtext;
    private int msrc;
    public MyView(Context context) {
        super(context);
    }
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        int textId = attrs.getAttributeResourceValue(null, "Text", 0);
        int srcId = attrs.getAttributeResourceValue(null, "Src", 0);
        mtext = context.getResources().getText(textId).toString();
        msrc = srcId;
    }
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        InputStream is = getResources().openRawResource(msrc);
        Bitmap mBitmap = BitmapFactory.decodeStream(is);
        int bh = mBitmap.getHeight();
        int bw = mBitmap.getWidth();
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        canvas.drawText(mtext, bw / 2, 30, paint);
    }
}

布局文件:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <com.example.myimageview2.MyView android:id="@+id/myView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        Text="@string/hello_world"
        Src="@drawable/xh"/>
</LinearLayout>

属性 Text、Src 在自定义 View 类的构造方法中读取。

2)通过 XML 为 View 注册属性,写法与 Android 提供的标准属性一样。

案例:实现一个带文字说明的 ImageView(ImageView + TextView 组合,文字说明可在布局文件中设置位置)

public class MyImageView extends LinearLayout {
    public MyImageView(Context context) {
        super(context);
    }
    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        int resourceId = -1;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyImageView);
        ImageView iv = new ImageView(context);
        TextView tv = new TextView(context);
        int N = typedArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.MyImageView_Oriental:
                    resourceId = typedArray.getInt(R.styleable.MyImageView_Oriental, 0);
                    this.setOrientation(resourceId == 1 ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
                    break;
                case R.styleable.MyImageView_Text:
                    resourceId = typedArray.getResourceId(R.styleable.MyImageView_Text, 0);
                    tv.setText(resourceId > 0 ? typedArray.getResources().getText(resourceId)
                            : typedArray.getString(R.styleable.MyImageView_Text));
                    break;
                case R.styleable.MyImageView_Src:
                    resourceId = typedArray.getResourceId(R.styleable.MyImageView_Src, 0);
                    iv.setImageResource(resourceId > 0 ? resourceId : R.drawable.ic_launcher);
                    break;
            }
        }
        addView(iv);
        addView(tv);
        typedArray.recycle();
    }
}

attrs.xml 进行属性声明,放在 values 目录下:

<resources>
    <declare-styleable name="MyImageView">
        <attr name="Oriental" format="enum">
            <enum name="Horizontal" value="1"></enum>
            <enum name="Vertical" value="0"></enum>
        </attr>
        <attr name="Text" format="string"></attr>
        <attr name="Src" format="reference"></attr>
    </declare-styleable>
</resources>

MainActivity 布局文件:先定义命名空间 xmlns:uview="https://schemas.android.com/apk/res/com.example.myimageview2"(包名为 manifest 中定义的包名),然后就能像使用系统属性一样使用 uview:Oriental="Vertical":

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:uview="https://schemas.android.com/apk/res/com.example.myimageview2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <com.example.myimageview2.MyImageView android:id="@+id/myImageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        uview:Text="这是一个图片说明"
        uview:Src="@drawable/tw"
        uview:Oriental="Vertical">
    </com.example.myimageview2.MyImageView>
</LinearLayout>

四、控件绘制

核心即 onDraw() 方法,在这里完成自定义内容的绘制。

五、自定义 View 的常用回调方法

onFinishInflate():应用从 XML 加载该组件并构建界面后调用;

onMeasure():检测 View 组件及其子组件的大小;

onLayout():需要为子组件分配位置和大小;

onSizeChange():组件大小改变时;

onDraw():组件将要绘制内容时;

onKeyDown / onKeyUp:按下 / 松开某个键盘时;

onTrackballEvent:发生轨迹球事件时;

onTouchEvent:发生触屏事件时;

onWindowFocusChanged(boolean):组件得到或失去焦点时;

onAttachedToWindow():把组件放入某个窗口时;

onDetachedFromWindow():把组件从某个窗口分离时;

onWindowVisibilityChanged(int):包含该组件的窗口可见性改变时。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved