问题
I am new to android. I want to create my own custom buttons in android;The methods which I have used to create the custom buttons are; 1. Draw a simple image whatever you want in paint and then go to drawable resources then paste that image.From there, we can use those images as buttons. Suppose my image is like this,

I made the rest of the portion of this image excluding green TRANSPARENT so that i will make only the green area touchable,for this I am using this code,
Bitmap TheBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.green);
int eventPadTouch = event.getAction();
int iX = (int) event.getX();
int iY = (int) event.getY();
int[] location = new int[2];
v.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
switch (eventPadTouch) {
case MotionEvent.ACTION_DOWN:
if (iX>=viewX & iY>=viewY & iX<=(viewX+TheBitmap.getWidth()) & iY<=(viewY+TheBitmap.getHeight())) {
if (TheBitmap.getPixel(iX,iY)!=0) {
Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
showPressedState();
return false;
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
showNormalState();
break;
}
return true;
}
But when I am making this image like this,


I found that this all is happening because android provides only limited types of layouts like LINEAR LAYOUT,RELATIVE LAYOUT,WEBVIEW. So ,is there any way to define our own layout means if i will be able to give the boudries of the layout.
回答1:
My idea is, that you manually check what is the color of pixel where you pressed, and based on that, you can switch different touch events (different color cases). I don't think there is easier way to achieve what you want to achieve.
But what if your image consist of gradient, or same colors in different clickable areas? Consider the following example:

As you can see there is a picture with 4 different color regions, but there is also a lot of white pixels in each region right? If a button background is not a solid color, but for example consist of gradients etc, then you could make each of them having different transparency
value (255,254,253 etc.) which wouldn't be noticeable by the user but which you could easily use to distinguish between area where you pressed.
So inside onClick method:
//Not sure about below line
alpha = ((bitmap.getPixel((int)event.getX(), (int)event.getY())) >>> 24);
switch(alpha)
{
case 255:
//your code
break;
case 254:
//your code
break;
default:
//your code
break;
}
Also, you might consider reading this:
- http://blahti.wordpress.com/2012/06/26/images-with-clickable-areas/
来源:https://stackoverflow.com/questions/17269046/define-the-layout-perimeters-manually-means-i-want-to-use-my-values-to-define-th