防止点击Android ImageVIew?

时间:2014-04-15 09:48:14

标签: java android android-layout click

我在ImageView内部有一个RelativeLayout覆盖,并希望阻止任何点击通过ImageView到其后面的按钮等(因此实际上会禁用整个RelativeLayout)。

这是一种更简单的方法,然后迭代RelativeLayout视图并将其设置为禁用,因为我目前正在使用此代码:

RelativeLayout rlTest = (RelativeLayout ) findViewById(R.id.rlTest);
for (int i = 0; i < rlTest.getChildCount(); i++) {
       View view = rlTest.getChildAt(i);
       view.setEnabled(true);
}

7 个答案:

答案 0 :(得分:34)

您可以将图像设置为

android:clickable="true"

答案 1 :(得分:18)

只需致电rlTest.setClickable(false)即可。这样可以防止点击传播给孩子们

答案 2 :(得分:9)

有一种更清洁的方式

您可以使用:

android:onClick="preventClicks"

在XML和您的活动中

public void preventClicks(View view) {}

这适用于片段。 这个Activity中的示例有多个片段相互重叠,只需在片段的背景中添加XML属性,它仍然会调用Activity.preventClicks并防止触及它背后的片段

答案 3 :(得分:4)

以下解决方案适用于一般情况:

_container.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // NOTE: This prevents the touches from propagating through the view and incorrectly invoking the button behind it
        return true;
    }
});

它通过将触摸事件标记为已处理,基本上阻止通过视图传播的任何触摸。  这适用于UI控件和布局容器(即:LinearLayout,FrameLayout等)。

将“clickable”设置为false的解决方案对于代码或视图XML中的布局容器不起作用。

答案 4 :(得分:1)

我假设您使用的是onClickListeners。

如何使用onTouchListener而不是onClickListeners。通过这样做,您可以控制层次结构的深度,甚至可以看到触摸。例如,如果您在相对布局(RL)和图像视图(IV)(包含在RL中)上有toch侦听器,并且您将touchListeners分配给它们。现在,如果您从IV的触摸事件中返回true ,则下方成员RL将不会收到触摸事件。但是,如果您从IV的触摸事件返回错误,则下方成员RL将收到触摸事件。

希望这有帮助!

答案 5 :(得分:1)

只需添加这两个侦听器:

    // Set an OnTouchListener to always return true for onTouch events so that a touch
    // sequence cannot pass through the item to the item below.
    view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);
            return true;
        }
    });
    // Set an OnHoverListener to always return true for onHover events so that focus cannot
    // pass through the item to the item below.
    view.setOnHoverListener(new OnHoverListener() {
        @Override
        public boolean onHover(View v, MotionEvent event) {
            v.onHoverEvent(event);
            return true;
        }
    });

答案 6 :(得分:0)

您可以使用数据绑定并像这样使用点击:

android:onClick="@{() -> true}"