Java .setOnClickListener(此);导致应用程序崩溃
目前正在为android开发tic-tac-toe游戏。我使用的是GameView,每次我运行我的应用程序时,它都会因为.setOnClickListener(这个)而崩溃;如果有人有什么有用的建议,那就太好了。 注意:按钮A1已放置在布局上Java .setOnClickListener(此);导致应用程序崩溃,java,android,button,onclick,Java,Android,Button,Onclick,目前正在为android开发tic-tac-toe游戏。我使用的是GameView,每次我运行我的应用程序时,它都会因为.setOnClickListener(这个)而崩溃;如果有人有什么有用的建议,那就太好了。 注意:按钮A1已放置在布局上 public class GameView extends View implements View.OnClickListener { private Paint bluePaint, redPaint; private Bitmap
public class GameView extends View implements View.OnClickListener {
private Paint bluePaint, redPaint;
private Bitmap a1Tile, a2Tile, a3Tile, b1Tile, b2Tile, b3Tile, c1Tile, c2Tile, c3Tile;
boolean playerTurn = true;
int playerTurnCount = 0;
private Button A1;
Button[] btnGridArray;
public GameView(Context context) {
super(context);
bluePaint = new Paint();
redPaint = new Paint();
bluePaint.setColor(Color.BLUE);
redPaint.setColor(Color.RED);
a1Tile = BitmapFactory.decodeResource(getResources(),R.drawable.a1tile);
a2Tile = BitmapFactory.decodeResource(getResources(),R.drawable.a2tile);
a3Tile = BitmapFactory.decodeResource(getResources(),R.drawable.a3tile);
b1Tile = BitmapFactory.decodeResource(getResources(),R.drawable.b1tile);
b2Tile = BitmapFactory.decodeResource(getResources(),R.drawable.b2tile);
b3Tile = BitmapFactory.decodeResource(getResources(),R.drawable.b3tile);
c1Tile = BitmapFactory.decodeResource(getResources(),R.drawable.c1tile);
c2Tile = BitmapFactory.decodeResource(getResources(),R.drawable.c2tile);
c3Tile = BitmapFactory.decodeResource(getResources(),R.drawable.c3tile);
A1 = (Button)findViewById(R.id.a1Btn);
btnGridArray = new Button[]{A1};
for(Button btn : btnGridArray){
btn.setOnClickListener(this);
}
}
@Override
protected void onDraw(Canvas canvas) {
//canvas.drawRect(100,100,100, 80, bluePaint);
canvas.drawBitmap(a1Tile, 60, 80, null);
canvas.drawBitmap(a2Tile, 280, 80, null);
canvas.drawBitmap(a3Tile, 500, 80, null);
canvas.drawBitmap(b1Tile, 60, 280, null);
canvas.drawBitmap(b2Tile, 280, 280, null);
canvas.drawBitmap(b3Tile, 500, 280, null);
canvas.drawBitmap(c1Tile, 60, 480, null);
canvas.drawBitmap(c2Tile, 280, 480, null);
canvas.drawBitmap(c3Tile, 500, 480, null);
redPaint.setTextSize(72);
}
@Override
public void onClick(View v){
Button btn = (Button) v;
btnClicked(btn);
}
public void btnClicked(Button btn){
if(playerTurn){
btn.setText("X");
btn.setTextSize(25);
}else{
btn.setText("O");
btn.setTextSize(25);
}
playerTurn = !playerTurn;
}
}
查看视图生命周期()。我的猜测是,您的视图尚未处于可以用作侦听器的状态。您正在获得NullPointerException,对吗?这是因为您正试图调用findViewById来搜索未膨胀到您的视图(GameView)中的视图。a1Btn来自哪里?@scana这是一个扩展的
视图
而不是活动
请发布您的布局。我认为您没有在您的应用程序中设置onClick
函数layout@ReazMurshed我知道这一点,它实际上应该扩展一个视图组,使其能够像他/她希望的那样工作。