在这种情况下,为什么听众没有正确设置

时间:2014-01-23 02:41:29

标签: android events view android-framelayout

在我的活动中,我显示了一个摄像头预览和一个我在其上绘制的按钮(一个看起来像按钮的view)。问题是,当我在该视图上设置单击侦听器时,无论我在屏幕上单击何处(即使在相机预览中),都会触发click事件。

这是代码:

    FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
    preview.addView(mCameraPreview);

    CameraButtonView cameraButton = new CameraButtonView(getBaseContext());
    preview.addView(cameraButton);

    cameraButton.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            Intent intent = new Intent(CameraTestActivity.this, MenuActivity.class);
            startActivity(intent);
            finish();
        }
    });

所以FrameLayout是相机预览。 CameraButtonView是在其上绘制的视图(位于底部的某个地方......它不占用太多空间)并且视图上确实设置了侦听器。

为什么当我点击FrameLayout上的任何地方时,我的事件会被触发?此外,我如何修复它,以便只有按钮订阅该事件。


相机按钮视图:

public class CameraButtonView extends View
{
Paint buttonPaint = new Paint();
Paint textPaint = new Paint();

SizeF size = new SizeF(500, 125);

public CameraButtonView(Context context)
{
    super(context);
    buttonPaint.setColor(Color.RED);
    textPaint.setColor(Color.BLACK);
    textPaint.setTextSize(35);
}

@Override
public void onDraw(Canvas canvas)
{
    RectF surface = RectangleHelper.create(0, 0, canvas.getWidth(), canvas.getHeight());
    PointF alignedPoint = RectangleHelper.align(surface, size, ContentAlignment.BottomCenter, AlignmentType.Internal);
    RectF content = RectangleHelper.create(alignedPoint, size);
    Rect textRectangle = new Rect();
    String buttonText = "Click to take a pic.";

    buttonPaint.getTextBounds(buttonText, 1, buttonText.length(), textRectangle);

    PointF alignedTextPoint = RectangleHelper.align(content, new SizeF(textRectangle.width(), textRectangle.height()), ContentAlignment.MiddleLeft, AlignmentType.Internal);

    canvas.drawRect(content, buttonPaint);
    canvas.drawText(buttonText, alignedTextPoint.x, alignedTextPoint.y, textPaint);
}
}

1 个答案:

答案 0 :(得分:1)

我的猜测是CameraButtonView上的layoutparams比按钮的实际外观大。尝试将layoutparms设置为新的LayoutParams(50,50)并查看它是否有帮助。然后你需要锻炼如何相对大小。

如果没有看到CameraButtonView的代码,我无法给出明确的答案。

更新(工作):

CameraButtonView cameraButton = new CameraButtonView(getBaseContext());
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(500, 125);
    layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
    cameraButton.setLayoutParams(layoutParams);
    preview.addView(cameraButton);