akrisanov akrisanov - 2 months ago 16
Android Question

Creating a click handler for the View in Android

I'm writing a very simple Android application that showing various shapes on the main view:

public class Figures extends Activity {
DemoView demoview;
int figure_type = 1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

demoview = new DemoView(this);
setContentView(demoview);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.color_menu_item:
break;
case R.id.circle_menu_item:
figure_type = 0;
break;
case R.id.square_menu_item:
figure_type = 1;
break;
case R.id.triangle_menu_item:
figure_type = 2;
break;
case R.id.exit_menu_item:
super.finish();
break;
default:
break;
}
return true;
}

private class DemoView extends View {
public DemoView(Context context) {
super(context);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);

if (figure_type == 0)
{
// circle
Random randomColor = new Random();
paint.setColor(randomColor.nextInt());
canvas.drawCircle(width/2, height/2-100, 100, paint);
}
else if (figure_type == 1)
{
// square
Random randomColor = new Random();
paint.setColor(randomColor.nextInt());
canvas.drawRect(80, 80, 220, 220, paint);
}
else if (figure_type == 2)
{
// triangle
Random randomColor = new Random();
paint.setColor(randomColor.nextInt());

Path path = new Path();
path.moveTo(width/2, 30);
path.lineTo(width/2+100, height/2-50);
path.lineTo(70, 190);
path.close();
canvas.drawPath(path, paint);
}
}
}
}


How to perform the event clicking on the screen (or DemoView)?

Answer Source

You need to set the onClickListener on your view. I.e in onCreate:

demo.setOnClickListener( new View.onClickListener() {
  public void  onClick  (View v) {
    // do click behavior here.
  });