【发布时间】:2010-09-22 22:13:57
【问题描述】:
我正在编写一个非常简单的 Android 应用程序,它在主视图上显示各种形状:
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);
}
}
}
}
如何执行点击屏幕(或DemoView)的事件?
【问题讨论】:
标签: android events views onclick