如何使视图对点击做出反应

时间:2011-04-05 20:52:20

标签: android android-widget

我创建了继承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"

/

&GT;

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对点击做出反应?

1 个答案:

答案 0 :(得分:2)

我可能会这样做:

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
  }
};

我不确定你是否真的可以将onClick放在视图定义中,就像你想要的那样,但我想如果有人能告诉我如何。