Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Creating shaped button

How can I create a custom button like this?

enter image description here

It should be just clickable area not a real button.

like image 264
xpepermint Avatar asked Oct 15 '11 14:10

xpepermint


1 Answers

I use a crapload of irregular shaped buttons on my app, and to change the "hot zone" or "clickable area" of the button, I just use the Bitmap.getPixel() method to check for alpha on the image used. If the method returns 0, then don't perform click event.

Example: (1) Create your button as usual, whichever way you would like. (2) Define a Bitmap and assign to it the same image drawable used for the button. (3) Get the X and Y coordinates of the touch or click action. (4) Pass the coordinates to the .getPixel(x,y) method.

Sample Code:

// ** Declare your Bitmap somewhere **
final Bitmap TheBitmap;       
TheBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.TheImage);

// ** My onTouch code **
public boolean onTouch(View v, MotionEvent event) {

        int eventPadTouch = event.getAction();

        switch (eventPadTouch) {

            case MotionEvent.ACTION_DOWN:
                if (iX>=0 & iY>=0 & iX<TheBitmap.getWidth() & iY<TheBitmap.getHeight()) { // ** Makes sure that X and Y are not less than 0, and no more than the height and width of the image.                
                    if (TheBitmap.getPixel(iX,iY)!=0) {
                        // * A non-alpha area was clicked, do something 
                    }               
                }
                return true;                
        }           
        return false;
}

The event.getX() and event.getY() simply give you the coordinates of where you touched the button.

** The above sample is to guide you in the correct direction. There are some checks to add to the code to assure no errors occur.

like image 168
2 revs Avatar answered Sep 30 '22 14:09

2 revs