检测视图外的触摸

时间:2014-12-01 20:32:40

标签: android view touch

我有一个自定义视图,我想知道,如果点击了我的视图之外的某些内容,我是否可以检测到这些特征。它必须在View类中,否则它不能像我预期的那样工作!

完整档案:https://github.com/Nicba1010/AndroidLibrary/blob/master/src/com/nicba1010/utils/views/PieChartView.java

OnTouchEvent(所以你知道我做了些什么)

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
        selected = null;
        invalidate();
        return true;
    }
    double deltaX = event.getX() - rect.width() / 2 - rect.left;
    double deltaY = -(event.getY() - rect.height() / 2 - rect.top);
    double fromMid = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    boolean inCircle = fromMid < (rectSelect.bottom / 2);
    if (inCircle) {
        double angleInDegrees = getPositionOnCircumference(deltaX, deltaY);
        float percentage = (float) (angleInDegrees / 360f);
        float totalPerc = 0;
        int index = -1, i = 0;
        for (PieChartSlice e : slices) {
            if (percentage > totalPerc) {
                index = i;
            } else if (percentage < totalPerc) {
                break;
            }
            totalPerc += e.getPercentage();
            i++;
        }
        if (index == -1) {
            Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
        } else {
            final PieChartSlice tmp = slices.get(index);
            addScaleTask(rect, 500, 0.9f, new Runnable() {
                @Override
                public void run() {
                    selected = tmp;
                }
            });
            selected = slices.get(index);
            invalidate();
            Toast.makeText(getContext(), selected.getName(),
                    Toast.LENGTH_SHORT).show();
            onSliceSelectedListener.onSliceSelected(this, selected);
        }
    } else {
        if (selected != null) {
            addScaleTask(rect, 500, 1f, new Runnable() {
                @Override
                public void run() {
                    selected = null;
                }
            });
            invalidate();
        }
    }
    return super.onTouchEvent(event);
}

1 个答案:

答案 0 :(得分:1)

ViewgetHitRect(Rect)方法。您可以使用它来检索此视图的rect,然后您可以使用此rect来检查它在其中的MotionEvent。例如

Rect rect = new Rect();
getHitRect(rect); 
if (rect.contains((int) event.getX(), (int) event.getY()) {

}