触摸屏接触点位置信息会传递给相应的view。
public class MyView extends View {
private final static String TAG = MyView.class.getSimpleName();
private Paint xLinePaint;
private Paint yLinePaint;
private Paint titlePaint;
private Paint rectPaint;
private String[] ySteps;
private String[] xWeeks;
//用来存放点击区域
private List<TouchArea> touchAreaList = new ArrayList<TouchArea>();
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init(){
ySteps = new String[]{"0", "2.5k","5k", "7.5k", "10k"};
xWeeks = new String[] { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
xLinePaint = new Paint();
yLinePaint = new Paint();
titlePaint = new Paint();
rectPaint = new Paint();
xLinePaint.setColor(Color.DKGRAY);
yLinePaint.setColor(Color.LTGRAY);
titlePaint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
height = height/2;
Log.d("111","width = " + width + "height = " +height);
canvas.drawLine(30,height,width,height,yLinePaint);
int heightStep = height/ySteps.length;
for (int i=1;i<ySteps.length+1;i++){
canvas.drawLine(30,height-heightStep*i,width,height-heightStep*i,yLinePaint);
canvas.drawText(ySteps[i-1],0,height-heightStep*(i-1),titlePaint);
}
int xStep = width/xWeeks.length;
int rectWidth = 20;
int rectHeight =300;
for (int j=1;j<xWeeks.length+1;j++){
canvas.drawRect(30+xStep*j-rectWidth/2,rectHeight,30+xStep*j+rectWidth/2,height,rectPaint);
canvas.drawText(xWeeks[j-1],xStep*j,height+30,titlePaint);
TouchArea touchArea = new TouchArea();
touchArea.setL(30+xStep*j-rectWidth/2);
touchArea.setT(rectHeight);
touchArea.setR(30+xStep*j+rectWidth/2);
touchArea.setB(height);
touchAreaList.add(touchArea);
}
Log.d("111","touchAreaList size" + touchAreaList.size());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_UP:
int x = (int)event.getX();
int y = (int)event.getY();
for (int i=0;i<touchAreaList.size();i++){
if(x<touchAreaList.get(i).getR()&&touchAreaList.get(i).getL()<x&&y<touchAreaList.get(i).getB()&&touchAreaList.get(i).getT()<y){
Log.d("111","click " + xWeeks[i]);
}
}
break;
default:break;
}
return true;
}
//用来存放点击区域
class TouchArea{
int l;
int t;
int r;
int b;
public int getL() {
return l;
}
public void setL(int l) {
this.l = l;
}
public int getT() {
return t;
}
public void setT(int t) {
this.t = t;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
}
点击图片上的RECF区域,将会判断出是星期几。