Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real custom shape of button

Given any shape (either filled circle, star, triangle, bitmap with transparent areas, etc.) I would like to know if it's possible (using the latest Android API) to know if the user has clicked on the view, or outside of it.

For example, if I have a circular button, I would like to know if the user has clicked inside the circle, but not outside of it.

Is it possible?

If not, maybe I could poll the pixel of the touch event, and if it's transparent, ignore it, and if it isn't, handle it as a click event?

like image 597
android developer Avatar asked Jul 01 '12 16:07

android developer


2 Answers

ImageView image=(ImageView) findViewById(R.id.imageView1);
image.setOnTouchListener(this);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();    

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    int pixel = bitmap.getPixel((int)event.getX(), (int)event.getY());
    int alphaValue=Color.alpha(pixel);
    return true;
}

This way you can get the alpha value of the pixel touched. Now you can easily check whether the pixel touched is transparent or not.

like image 85
Adnan Zahid Avatar answered Nov 13 '22 02:11

Adnan Zahid


I also wanted to do something like that and i ended up tweaking with the FrameLayout. FrameLayout allows you to add multiple views on top of each other.

Add a FrameLayout. Inside that you can add a 'View' and set its height and width to match_parent. On top of the View, add the buttons you want to.

Then in your code, get the reference of the View and set onClickListener on it so that whenever user touches that View, you can handle that event. Set click listeners on other buttons as well.

Now just handle your touch events. You will now know if the user has clicked on the button or outside it (user has clicked on the View).

If you want to create transparent or translucent buttons, check https://stackoverflow.com/a/11689915/1117338. I hope this helps.

like image 2
Vikram Gupta Avatar answered Nov 13 '22 01:11

Vikram Gupta