按下按钮时Android移动图像

时间:2013-02-24 20:28:34

标签: android image onclick pressed

我想在按下按钮时移动播放器图像。我尝试了onClick()方法,但它不起作用。 按下向上按钮时,播放器应向上移动一些像素。 我尝试过像我在Android Developer Page上看到过的getButtonState之类的东西, 但我不明白这是怎么回事...... 有什么建议?

private Context mContext;
int enemy_x = -1;
int enemy_y = -1;
int player_x = -1;
int player_y = -1;

private int enemy_xVelocity = 15;
private int enemy_yVelocity = 0;
private int player_xVelocity = 0;
private int player_yVelocity = 10;
private Handler h;
private final int FRAME_RATE = 60;

Button upbutton = (Button) findViewById(R.id.upbutton);

public AnimatedView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    h = new Handler();
}

private Runnable r = new Runnable() {
    @Override
    public void run() {
        invalidate();
    }
};

protected void onDraw(Canvas c) {
    BitmapDrawable enemy = (BitmapDrawable) mContext.getResources()
            .getDrawable(R.drawable.enemy);
    BitmapDrawable player = (BitmapDrawable) mContext.getResources()
            .getDrawable(R.drawable.player);

    // enemy movement
    if (enemy_x < 0 && enemy_y < 0) {
        enemy_x = this.getWidth() / 2;
        enemy_y = this.getHeight() / 2;
    } else {
        enemy_x += enemy_xVelocity;
        enemy_y += enemy_yVelocity;
        if ((enemy_x > this.getWidth() - enemy.getBitmap().getWidth())
                || (enemy_x < 0)) {
            enemy_xVelocity = enemy_xVelocity * -1;
        }
        if ((enemy_y > this.getHeight() - enemy.getBitmap().getHeight())
                || (enemy_y < 0)) {
            enemy_yVelocity = enemy_yVelocity * -1;
        }
    }

    // player movement

    if (player_x < 0 && player_y < 0) {
        player_x = (this.getWidth() / 2) - 20;
        player_y = this.getHeight() - 150;
    } else {


        player_x += player_xVelocity;
        player_y += player_yVelocity;
        if ((player_x > this.getWidth() - player.getBitmap().getWidth())
                || (player_x < 0)) {
            player_xVelocity = player_xVelocity * -1;
        }
        if ((player_y > this.getHeight() - player.getBitmap().getHeight())
                || (player_y < 0)) {
            player_yVelocity = 0;
        }

    }

    c.drawBitmap(enemy.getBitmap(), enemy_x, enemy_y, null);
    c.drawBitmap(player.getBitmap(), player_x, player_y, null);
    h.postDelayed(r, FRAME_RATE);
}

0 个答案:

没有答案