android与其他GUI应用开发一样,也提供了自定义控件的定制。本文中给出一个自定义processbar的例子,如下:
![](https://img7.php1.cn/3cdc5/cb94/339/32d4aaeb400a58ec.png)
例子中,控件能够定义进度条已实现和未实现的颜色属性,并且用asynctask以每秒一格的速度刷新。
1. 在values下增加attr.xml,定义MyProcessBar的属性
2. 实现自定义的MyProcessBar类
public class MyProcessbar extends View {private Paint mPaint;private int current = 0;private int end = 10;private int color1;private int color2;public MyProcessbar(Context context, AttributeSet attrs) {super(context, attrs);mPaint = new Paint();TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyProcessbar); color1 = a.getColor(R.styleable.MyProcessbar_color1,0); color2 = a.getColor(R.styleable.MyProcessbar_color2,0); a.recycle();}public MyProcessbar(Context context) {super(context);mPaint = new Paint();}//用以更新ProcessBarpublic void setCurAndEnd(int cur, int end){current = cur;end = end;invalidate();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);mPaint.setStyle(Style.FILL);mPaint.setColor(color1);for(int i = 0; i }
3. 在layout中使用该自定义控件
4. 在Activity中启动一个异步任务更新该控件,异步任务实现如下:
public class MyTask extends AsyncTask {private MyProcessbar mprogressbar;public MyTask(MyProcessbar mprogressbar) {super();this.mprogressbar &#61; mprogressbar;}&#64;Overrideprotected String doInBackground(String... params) {int i &#61; 0;for(i &#61; 0; i <10; i&#43;&#43;){try {Thread.sleep(1000);publishProgress(i); } catch (InterruptedException e) {e.printStackTrace();}}return i &#43; "&" &#43; params[0];}&#64;Overrideprotected void onProgressUpdate(Integer... values) {mprogressbar.setCurAndEnd(values[0], 10);}
}
备注&#xff1a;
自定义控件此例中主要用到onDraw方法&#xff0c;其他主要接口还有onMeasure和onLayout&#xff0c;
1. onMeasure 属于View的方法&#xff0c;用来测量自己和内容的来确定宽度和高度 &#xff0c;view的measure方法体中会调用onMeasure
2. onLayout 属于ViewGroup的方法&#xff0c;用来为当前ViewGroup的子元素的位置和大小