2
보기를 상속 한 맞춤 위젯을 만들었습니다.클릭하면 반응하는 방식
<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가 클릭에 반응하지 않는다는 것입니다. 나는 파견 행사의 재정의 (override)가 있지만 들어 가지 않습니다. 아무도 도와 줄 수 있습니까? 이 ElementView를 클릭시 반응하도록하려면 어떻게해야합니까? 당신이하려고하는 것처럼 당신이 실제로 뷰 정의 내부의 온 클릭을 넣을 수있는 경우
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
}
};
잘 모르겠어요,하지만 어떻게 이드처럼에게 누군가가 나를 보여줄 수있는 경우 :
감사합니다. 지금 입력되지만 색상을 변경할 수 없습니다! 그것은 코드를 통과하지만보기는 동일하게 유지됩니다. – Damir
ElementView에서 색상 변경을 처리하는 public 함수를 만들 수도 있습니다. 그런 다음 해당 함수를 onClick에서 호출합니다. ev.changeColor (someVar); – sgarman
onClick 물건 처리가 끝나면보기에서 invalidate()를 호출하여 강제로 다시 그려 볼 수도 있습니다. –