我创建了一个自定义ImageButton,用于改变简单游戏中对象的方向。单击/触摸该按钮时按钮没有响应。 我尝试过setOnTouchListener和setOnClickListener但没有任何反应。
的CustomButton:
public class CustomButton extends ImageButton {
private Bitmap bitmap;
public CustomButton(Context context, int resource) {
super(context);
setClickable(true);
bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
}
public Bitmap getBitmap() {
return bitmap;
}
GameView:
public class GameView extends SurfaceView implements Runnable {
volatile boolean playing;
private Thread gameThread = null;
private CustomButton mLeftButton;
private Player player;
private Paint paint;
private Canvas canvas;
private Bitmap bitmap;
private SurfaceHolder surfaceHolder;
public GameView(Context context, int screenX, int screenY) {
super(context);
mLeftButton = new CustomButton(context, R.drawable.boom);
mLeftButton.setImageBitmap(mLeftButton.getBitmap());
mLeftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"It worked",Toast.LENGTH_LONG).show();
}
});
player = new Player(context, screenX, screenY);
surfaceHolder = getHolder();
paint = new Paint();
}
@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
private void update() {
player.update();
}
private void draw() {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(player.getBitmap(), player.getX(), player.getY(), paint);
canvas.drawBitmap(mLeftButton.getBitmap(), 20, 20, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
答案 0 :(得分:1)
您创建按钮但不将其链接到当前布局。
在绘图方法中,您只需绘制图像而不将其功能添加到SurfaceView
,这样就不会使用按钮功能。
我建议以按钮位于表面视图上的方式创建基本xml布局(例如RelativeLayout
或FrameLayout
),然后设置{{1}你要为按钮设置onclicklistener并将其连接到包含视图。