将TouchDelegate展开到超出视图的父级

时间:2016-09-13 13:06:32

标签: android

我有一个如下所示的布局:

enter image description here

我正在尝试扩展绿色视图的可点击区域。我用于此目的的代码是:

public static void setTouchDelegate(View view, float dimen) {
    final View parent = (View) view.getParent();
    parent.post( () -> {
        final Rect delegateArea = new Rect();
        view.getHitRect(delegateArea);
        delegateArea.right += dimen;
        delegateArea.left -= dimen;
        delegateArea.bottom += dimen;
        delegateArea.top -= dimen;

        parent.setTouchDelegate( new TouchDelegate( delegateArea , view));
    });
}

红色区域是绿色视图的父级。问题是,无论我试图设置多大的TouchDelegate,它总是只适用于父红色区域。我可以覆盖整个红色区域以便点击,但我无法将可点击区域扩展到蓝色区域。

我的假设是,这不是我的代码中的问题,而是TouchDelegate的正常行为。

问题是:如何在下面的预览中为绿色视图设置看似紫色区域的可点击区域?

enter image description here

//编辑:

这是项目的布局 - 带文本的红色矩形和绿色的ImageButton:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_dark"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:gravity="center_vertical"
android:paddingBottom="3dp"
android:paddingLeft="10dp"
android:paddingRight="4dp"
android:paddingTop="3dp">

<TextView
    android:id="@+id/item_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:paddingRight="18dp"
    android:textColor="@android:color/black"
    android:textSize="12sp"
    android:textStyle="bold"
    tools:text="Test" />

<ImageButton
    android:id="@+id/item_green"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|center_vertical"
    android:background="@android:color/transparent"
    android:src="@android:color/holo_green_light" />

</FrameLayout>

1 个答案:

答案 0 :(得分:0)

基本上,您需要设置相对于视图祖先的委托区域,并在此祖先上设置TouchDelegate。

图像中的目标祖先是蓝色背景的视图。

     1     2     3     4
 1 [A,A] [B,D] [C,G] [D,J]
 2 [A,B] [B,E] [C,H] [D,K]
 3 [A,C] [B,F] [C,I] [D,L]

由于原始版本https://gist.github.com/patrickhammond/6d49e9ac08f96bd8d302#gistcomment-2385782中的错误,最好使用修改后的TouchDelegate。

相关问题