简体   繁体   中英

Android fully shaped Button

I tried to change the shape of some Android components like Button or View. What I can do is assign a shape to the background with the onDraw-Method. Well, it looks like reshaped, but the touch-events will still work outside my defined shape. Is there any practicable way to exclude touches outside my shape? Certainly, I could check every position of the mouse-event, but for complexer shapes, I don't know how to check if a point is inside the shape. Thanks for all your replies.

Simon

You can define the shapes in xml (as you can see here) . eg :

drawable/sample_shape.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Then you can use the xml description as a drawable for an ImageButton .

drawable/samplebutton.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/sample_shape" /> <!-- pressed -->
    <item android:state_focused="true"
       android:drawable="@drawable/sample_shape" /> <!-- focused -->
    <item android:drawable="@drawable/sample_shape" /> <!-- default -->
</selector>

in your layoutfile:

<ImageButton 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:background="@drawable/samplebutton">
</ImageButton>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM