Bounds in custom triangle button

2019-09-14 19:06发布

问题:

I created a custom button as shown in the image. My problem is that the bounds still clickble. Is there any way to wrap the triangle.

Image custom button

My shape xml file :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <rotate
        android:fromDegrees="45"
        android:toDegrees="45"
        android:pivotX="-10%"
        android:pivotY="87%" >
        <shape
            android:shape="rectangle" >
            <stroke  android:color="@color/transparent" android:width="30dp"/>
            <solid 
             android:color="@android:color/black" />

        </shape>
    </rotate>
</item>
</layer-list>

Button:

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:weightSum="1">

    <Button
        android:layout_width="114dp"
        android:layout_height="match_parent"
        android:background="@drawable/triangle"
        android:id="@+id/button"/>

    </LinearLayout>

I also tried canvas approach and get the same problem.

回答1:

Sorry for my late reply. I don't know you have found the solution yet. Because android:pivotX="-10%" ,your black triangle have distance with the top edge.

You can remove android:pivotX, android: pivotY, and add android:layout_marginBottom="-50dp"in your button like this:

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:weightSum="1"
android:layout_marginBottom="-50dp"
>

<Button
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/triangle"
    android:id="@+id/button"
    />
</LinearLayout>

Now your black triangle has no distance with the top edge. But it doesn't really wrap the triangle. If you want to wrap the triangle, there are some solution (It's Not Easy):

You can override the OnTouch Event method in a CustomView / CustomButton.

Inside you have the MotionEvent were you can check if the Touch was inside your Triangle (with the help of some mathematics :P)

Or you can do the same:

Android Custom Shape Button