カスタムビューのクラスがあります。方法の1つは
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint ();
Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
canvas.drawColor(Color .BLACK);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
int left = canvas.getWidth()/2 - wrench.getWidth()*2 + j*wrench.getWidth();
int top = 0 + i*wrench.getHeight();
canvas.drawBitmap(wrench, left, top, null);
regions = new ArrayList<Region>();
Region reg = new Region(left, top, left + wrench.getWidth(), top + wrench.getHeight());
regions.add(reg);
// int right = left + wrench.getWidth();
// int bottom = top + wrench.getHeight();
// Log.d("REGION", left + "," + top + "," + right + "," + bottom);
}
}
}
私の形には8つの領域があります。だから、アクティビティクラスで
playField = (PlayGameView) findViewById(R.id.play_field_surface_view);
playField.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// if(playField.getRegions().contains(210, 10)) {
ArrayList<Region> regions = playField.getRegions();
for(Region region: regions ) {
boolean condition = region.contains( (int)event.getX(), (int)event.getY());
if(condition) {
Toast.makeText(PlayGameActivity.this, (int)event.getX() + " " + (int)event.getY(), 2000).show();
}
}
return true;
}
});
しかし、それは機能しません!最後の形をクリックするとトーストが2回呼び出されます!しかし、他の形ではそれは時々呼ばれます....私を助けてください^ _ ^
したがって、このコードは正常に機能します)
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint ();
Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
canvas.drawColor(Color .BLACK);
shapeWidth = wrench.getWidth();
shapeHeight = wrench.getHeight();
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
int left = canvas.getWidth()/2 - wrench.getWidth()*2 + j*wrench.getWidth();
int top = i*wrench.getHeight();
canvas.drawBitmap(wrench, left, top, null);
shapeLeft[j] = left;
shapeTop[i] = top;
}
}
}
public ArrayList<Region> getRegions() {
regions = new ArrayList<Region>();
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
Region reg = new Region(shapeLeft[j], shapeTop[i], shapeLeft[j] + shapeWidth, shapeTop[i] + shapeHeight);
regions.add(reg);
// int right = left + wrench.getWidth();
// int bottom = top + wrench.getHeight();
// Log.d("REGION", left + "," + top + "," + right + "," + bottom);
}
}
return regions;
}
と
playField = (PlayGameView) findViewById(R.id.play_field_surface_view);
playField.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// if(playField.getRegions().contains(210, 10)) {
ArrayList<Region> regions = playField.getRegions();
for(Region region: regions ) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
boolean condition = region.contains( (int)event.getX(), (int)event.getY());
if(condition) {
Toast.makeText(PlayGameActivity.this, (int)event.getX() + " " + (int)event.getY(), 2000).show();
}
}
}
return true;
}
});