如何创建这样的自定义按钮?

时间:2015-09-12 21:50:44

标签: android button android-custom-view

如何创建具有自定义触控区域的按钮?
我想创建如下所示的弯曲按钮:

enter image description here

但只有曲线下的区域应该是可点击的,所以简单的ImageButtons不会起作用,因为hitbox是矩形的。

1pic。如何使用ImageButtons
2pic。其中一个版本必须是

enter image description here

2 个答案:

答案 0 :(得分:1)

视图本质上是矩形

因此,只需将背景图像放在容器布局中,然后将(透明)ImageViews或TextViews(内部没有任何图像或文本)放在上面。
并对他们的点击监听器作出反应。

这是基本的想法:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rise_call_bg"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        >
        <TextView
            android:id="@+id/txtLeft"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtMidLeft"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtMidRite"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtRite"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
    </LinearLayout>
</RelativeLayout>

结果是这样的:

enter image description here

每个TextView都是可点击的 所以,只需添加点击监听器(一个集中的或一个 - 你选择的),就完成了。

用户会认为按钮是他/她所看到的:TextViews下面的绘制文本。

注意:我选择了所有TextView,只是为了让它们在设计时可见 它们在运行时将完全透明。

你可能想要提高一点,比如高达120dp。

答案 1 :(得分:1)

尝试使用此解决方案。 核心思想是检测是否触摸位图。

https://stackoverflow.com/a/22325218/1979882