所以我试图做一个画布与菜单选项之间切换画一条线和一个圆圈但我有麻烦显示菜单
public class MainActivity extends AppCompatActivity {
final static int LINE = 1, CIRCLE = 2;
static int curShape = LINE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyGraphicView(this));
}
public class MyGraphicView extends View{
int startX = -1, startY = -1, stopX = -1, stopY = -1;
public MyGraphicView(Context context)
{ super(context); }
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) event.getX();
startY = (int) event.getY(); break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
stopX = (int) event.getX();
stopY = (int) event.getY();
this.invalidate();
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
switch (curShape) {
case LINE: canvas.drawLine(startX, startY, stopX, stopY, paint);
break;
case CIRCLE: int radius = (int) (Math.sqrt(Math.pow(stopX-startX, 2))
+Math.sqrt(Math.pow(stopX-startX, 2)));
canvas.drawCircle(startX, startY, radius, paint); break;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0, 1, 0, "Drawing line");
menu.add(0, 2, 0, "Drawing circle");
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case 1: curShape = LINE; return true;
case 2: curShape = CIRCLE; return true;
}
return super.onContextItemSelected(item);
}
}
}
这是代码,我也试过把菜单代码放在主活动类中,但它不起作用,我该怎么办。我也遇到了与onOptionsItemSelected相同的问题
2条答案
按热度按时间vd2z7a6w1#
正如这里所看到的,方法
onCreateOptionsMenu(...)
应该被重写或者...在
Activity
中:或
Fragment
:ctrmrzij2#
我采用了与您提供的相同的代码,并以您可以使用customView类中的menuOptions的方式进行了更新
希望这将清楚你的概念