How to make view react on click
I have created custom widget which inherits View.
<com.test.www.view.ElementView
android:id="@+id/surface1"
android:layout_width="wrap_content"
android:layout_height="wrap_conte开发者_如何学Cnt"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_weight="1"
/
>
and
public class ElementView extends View {
private final int width=100;
private final int height=100;
private Paint paint=null;
private Canvas canvas=null;
public ElementView(Context context) {
super(context);
paint = new Paint();
}
public ElementView(Context context, AttributeSet attr) {
super(context, attr);
paint = new Paint();
}
public ElementView(Context context, AttributeSet attr, int defaultStyles) {
super(context, attr, defaultStyles);
paint = new Paint();
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
int measuredWidth = MeasureSpec.getSize(widthSpec);
int measuredHeight = MeasureSpec.getSize(heightSpec);
setMeasuredDimension(this.width,this.height);
}
@Override
protected void onDraw(Canvas canvas) {
this.canvas=canvas;
// get the size of your control based on last call to onMeasure
int height = getMeasuredHeight();
int width = getMeasuredWidth();
// Now create a paint brush to draw your widget
paint.setColor(Color.GREEN);
//define border
this.canvas.drawLine(0, 0, 0, 99, paint);
this.canvas.drawLine(0, 0, 99,0, paint);
this.canvas.drawLine(99, 0, 99, 99, paint);
this.canvas.drawLine(0, 99, 99,99, paint);
//define cells
this.canvas.drawLine(0,50,99,50,paint);
this.canvas.drawLine(30,0,30,50,paint);
//draw green rectangle
this.canvas.drawRect(new Rect(0,0,50,50),paint);
//draw some text
paint.setTextSize(8);
paint.setColor(Color.RED);
String displayText = "test";
Float textWidth = paint.measureText(displayText);
int px = width / 2;
int py = height / 2;
this.canvas.drawText(displayText, px - textWidth / 2, py, paint);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
paint.setColor(Color.RED);
//change color of first cell
canvas.drawRect(new Rect(0,0,50,50),paint);
return super.dispatchTouchEvent(event);
}
}
Problem is that this ElementView doesn't react on click. I have override of dispatch event but it doesn't come in. Can anybody help me ? What to do to make this ElementView react on click ?
I would probably do something like this:
ElementView ev = (ElementView)findViewById(R.id.surface1);
ev.setOnClickListener(evOnClick);
public OnClickListener evOnClick = new OnClickListener() {
@Override
public void onClick(View v, int arg1) {
//DO ONCLICK STUFF
}
};
I'm not sure if you can actually put the onClick inside the view definition like you are trying to, but Id like if someone could show me how.
精彩评论