android - 选择器正在将更改应用于所有 View 而不是单击的 View

标签 android android-custom-view viewgroup

我正在努力向 Android 中的拖放网格中的 View 添加 onClick 突出显示。该项目位于GitHub (dev 分支包含使用选择器的代码)。

我遇到的问题是在适配器中,当我将 onClick 选择器设置为 View 的背景时,当我单击 View 时,选择器不会仅更改该 View 的背景,而是会更改所有 View 的背景。

我很确定这是 ViewGroup 中 onTouch 中处理点击的方式造成的(如下)。我不确定是否应该以不同的方式返回 true/false 或以不同的方式触发 onClick 监听器以防止突出显示所有 View 。

感谢任何想法/帮助,谢谢。

@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        touchDown(event);
        break;
    case MotionEvent.ACTION_MOVE:
        touchMove(event);
        break;
    case MotionEvent.ACTION_UP:
        touchUp(event);
        break;
    }
    if (aViewIsDragged())
        return true;
    return false;
}

private void touchUp(MotionEvent event) {
    if(dragged == -1) {
        if(onClickListener != null) {
            View clickedView = getChildAt(getTargetAtCoor((int) event.getX(), (int) event.getY()));
            if(clickedView != null)
                onClickListener.onClick(clickedView);
        }
    } else {
        manageChildrenReordering();
        hideDeleteView();
        cancelEdgeTimer();

        movingView = false;
        dragged = -1;
        lastTarget = -1;
        container.enableScroll();
        cancelAnimations();
    }
}

编辑:查看 ViewGroup 文档后 android:addStatesFromChildren听起来像是我正在寻找的,但似乎没有任何效果。

android:addStatesFromChildren

Sets whether this ViewGroup's drawable states also include its children's drawable states. This is used, for example, to make a group appear to be focused when its child EditText or button is focused.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol addStatesFromChildren.

更新

我已经找到解决这个问题的方法了。拉取请求是 here

最佳答案

编辑

layout.setClickable(true); 添加到 View 函数(第 133 行和第 156 行之间的某个位置)以使每个项目都可单击。这是他们拥有自己的可选择状态所必需的。如果没有它,网格就会接收到触摸,并且该状态会传递给每个 child 。这会破坏您的 onTouch 功能,但这将是一个单独的问题。

如果您不想担心更改 onTouch 的功能,您可以在不同的触摸功能中手动更改所选项目的背景,而不是使用选择器


原文没有捕获要点:

也许我遗漏了一些东西,但我认为您可以从 onTouch 传递 View “v”并将其用作 clickedView,而不是尝试根据位置找出它是哪个 View 。

关于android - 选择器正在将更改应用于所有 View 而不是单击的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13825463/

相关文章:

安卓: Canvas 不缩放

android - onMeasure 没有在我的自定义 View 组 android 中被调用

android - 布局,将 View 添加到 View 组中,并将它们显示在行中,因此不需要滚动

android - 将大文本文件添加到 Assets 文件夹

android - SetNextFocusDownId 行为不正确

java - 为Google map 创建插件

Android 如何使用 Espresso 检查 ImageView 的内容

android - 如何在自定义 View 中添加 View ?

android - RecyclerView 和数据绑定(bind)不起作用

android - 将布局添加到 View 组。