2
我已創建了繼承View的自定義窗口小部件。如何使查看對點擊產生反應
<com.test.www.view.ElementView
android:id="@+id/surface1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_weight="1"
/
>
和
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);
}
}
問題是,這ElementView不上點擊反應。我有調度事件的重寫,但它不進來。任何人都可以幫助我嗎?如何使這個ElementView在點擊時作出反應?
謝謝,它現在進入,但我不能改變顏色!它通過代碼通過,但視圖保持不變。 – Damir 2011-04-05 21:28:11
也許在ElementView中創建一個公共函數來處理顏色變化。然後在onClick中調用該函數:ev.changeColor(someVar); – sgarman 2011-04-05 21:31:34
您可以嘗試在處理onClick事件結束時在視圖上調用invalidate(),強制重繪。 – 2011-04-05 22:40:00