我正在尝试在用户触摸时创建几个圆圈,如果他们再次触摸取决于他们触摸的位置,另一个人会显示...但是当我使用ontouch事件时...它会崩溃...我是新手方式,我该如何解决?
public class GameView extends View{
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public GameView(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
public class GameActivity extends Activity {
/** Called when the activity is first created. */
GameView gm;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.my_view);
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(final View v, MotionEvent e) {
final float x = e.getX();
final float y = e.getY();
final Handler handler = new Handler()
{
public void handleMessage(Message msg) {
gm.postInvalidate();
}
};
Thread graphicThread = new Thread()
{
public void run() {
try {
//Do the drop
FrameLayout flView = (FrameLayout) v;
flView.addView(new GameView(getParent(), x,y,25));
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
boolean isRunning=true;
graphicThread.start();
return true;
}
});
}
}
答案 0 :(得分:1)
它可能是真的,但你做过的一件事就是实例化你的gm
。当你这样做时
gm.postInvalidate();
你可能得到nullpointerexception
。这还不够:
GameView gm;
你需要实际打电话
gm = new GameView(/*insert stuff here*/);