2012年8月27日7:17:09自定义控件一般可以基于所有控件类的基类View来实现。它可以具有公开或者保护的属性、方法、还可以具有自己的xml属性。布局文件中,自定义控件的使用方法和预定义控件的使用是类似的。
自定义控件可以在本应用程序包中实现功能的复用,但是不能跨程序包使用。
一、View具有以下三个构造函数,分别用于在不同的场合产生View:
public View(Context context) //简单构造
public View(Context context, AttributeSet attrs) //带有属性
public View(Context context, AttributeSet attrs, int defStyle) //带属性和默认值
二、关键方法
(1) View类中的一系列方法,用于View的运行周期内的特定时刻调用。通过实现定制实现这些方法可以定制View行为:
protected void onFinishInflate() //此方法将在布局XML文件Infalte完成的时刻被调用
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) //用于确认View及其孩子要求的尺寸;
protected void onLayout(boolean changed, int left, int top, int right, int bottom) //用于在View完成时给它的孩子们分配好尺寸和位置的时刻调用;
protected void onSizeChanged(int w, int h, int oldw, int oldh) //用于在View的尺寸发生变化的时候调用;
protected void onDraw(Canvas canvas) //是View类的核心方法,在绘制的时候被调用,这是一个用于确定View外观的关键方法。
一般情况下,在一个控件的构建过程中,依次调用onFinishInflate()、onMeasure()、onLayout()和onDraw()方法。
(2) 设备相关事件处理方法:
public boolean onKeyDown(int keycode, KeyEvent event) //按键按下事件
public boolean onKeyUp(int keycode, KeyEvent event) //按键抬起事件
public boolean onTouchEvent(MotionEvent event) //触摸屏事件
public boolean onTrackballEvent(MotionEvent event) //轨迹球事件
(3) 与聚焦相关的方法:
public void onWindowFocusChanged(boolean hasWindowFocus) //包含当前控件的窗口聚焦改变的情况下被调用
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)//当前控件的聚焦发生变化的时候被调用;
实例:自定义TextView
testView.java
- public class testView extends View
- {
- Paint mPaint;
- public testView(Context context)
- {
- super(context);
- }
-
- public testView(Context context, AttributeSet attrs)
- {
- super(context, attrs);
- mPaint = new Paint();
- TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.testView);
- //提供默认值放置位置未定
- int textColor = array.getColor(R.styleable.testView_textColor, 0xFF00ff00);
- float textSize = array.getDimension(R.styleable.testView_textSize, 36);
- mPaint.setColor(textColor);
- mPaint.setTextSize(textSize);
- array.recycle();
- }
-
- public void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- mPaint.setStyle(Style.FILL);
- canvas.drawRect(10, 10, 100, 100, mPaint);
- mPaint.setColor(Color.BLUE);
- canvas.drawText("自定义View测试", 10, 120, mPaint);
- }
- }
styleable.xml- <resources>
- <declare-styleable name="testView">
- <attr name="textColor" format="color"/>
- <attr name="textSize" format="dimension"/>
- </declare-styleable>
- </resources>
布局文件:- <RelativeLayout xmlns:android=""
- xmlns:tools=""
- android:layout_width="match_parent"
- android:layout_height="match_parent" xmlns:app="">
- <com.example.test002.testView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- ></com.example.test002.testView>
- </RelativeLayout>
源码:
test002.zip 这份代码有点小问题,等再修改吧上班了要~
阅读(624) | 评论(0) | 转发(0) |