作者:sundroid
个人站点:sundroid.cn 邮箱: hfutsnjc@163.com 微博:http://weibo.com/Sundroid
本文编码(utf-8)http://download.csdn.net/detail/hfut11/7899653
效果图
自定义View CustomView继承View,重写父类onDraw函数。
package com.sundroid.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
public class CustomView extends View {
// 图形类型
int type = 0;
// 重写父类onDraw函数
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(10);
switch (type) {
// 画圆形
case 0:
canvas.drawCircle(200, 200, 100, paint);
break;
// 画矩形
case 1:
canvas.drawRect(60, 90, 360, 100, paint);
break;
// 三角形
case 2:
Path path = new Path();
path.moveTo(80, 100);
path.lineTo(420, 250);
path.lineTo(80, 350);
path.close();
canvas.drawPath(path, paint);
break;
default:
break;
}
}
public void changeType() {
type++;
if (type > 2) {
type = 0;
}
}
// 构造函数
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
}
package com.sundroid.customview;
import com.sundroid.widget.CustomView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private CustomView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customView = (CustomView) findViewById(R.id.custView);
customView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Message message = new Message();
message.what = 1;
myHandler.sendMessage(message);
}
});
}
Handler myHandler = new Handler() {
// 接收到消息后处理
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
customView.changeType();
customView.invalidate();
break;
default:
break;
}
super.handleMessage(msg);
}
};
}