无法使invalidate语句生效

时间:2014-04-17 02:28:06

标签: java android

    package com.game.crazyeights;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
import com.game.crazyeights.R;


public class TitleView extends View {

    private Bitmap titleGraphic;
    private Bitmap playButtonUp;
    private Bitmap playButtonDown;
    private boolean playButtonPressed;
    private int screenH;
    private int screenW;

    public TitleView(Context context) {
        super(context);
        titleGraphic = BitmapFactory.decodeResource(getResources(), R.drawable.titlegraphic);
        playButtonUp = BitmapFactory.decodeResource(getResources(), R.drawable.play_button_up);
        playButtonDown = BitmapFactory.decodeResource(getResources(), R.drawable.play_button_down);
    }

    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        screenW = w;
        screenH = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(titleGraphic, (screenW-titleGraphic.getWidth())/2 , 0, null);
        if (playButtonPressed) {
            canvas.drawBitmap(playButtonDown, (screenW-playButtonUp.getWidth())/2, (int)(screenH*0.7), null);
        } else {
            canvas.drawBitmap(playButtonUp, (screenW-playButtonUp.getWidth())/2, (int)(screenH*0.7), null);
        }
    }

    public boolean onTouchedEvent(MotionEvent event) {
        int eventaction = event.getAction();
        int X = (int)event.getX();
        int Y = (int)event.getY();

        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
            if (X > (screenW-playButtonUp.getWidth())/2 && X < (screenW-playButtonUp.getWidth())/2 + playButtonUp.getWidth() && Y > (int) (screenH*0.7) && Y < (int) (screenH*0.7) + playButtonUp.getHeight()) {
                playButtonPressed = true;
            }
            break;

        case MotionEvent.ACTION_MOVE:
            break;

        case MotionEvent.ACTION_UP:
            playButtonPressed = false;
            break;
    }
        invalidate();
        return true;
    }
}

基本上,我试图在最后添加一个无效的重绘屏幕以更新按钮状态。我的意思是,当按下按钮时,它的图片处于我想要更新的不同状态,但是当我使用无效时它不会这样做。当用户放开按钮时,它会更新回常规按钮状态图像..

如果你不明白我上面所说的,那就试着简化吧。我希望按钮在按下时更新其图像,并在您停止按下按钮时返回到上一个图像。我尝试使用invalidate但是,它没有用。这有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您不应将invalidate()放在方法的末尾。每次触摸或移动OnTouchedEvent()时都会触发View

确保调用MotionEvent.ACTION_DOWN中的案例。我的意思是那些布尔表达式是有效的。然后在案件结束时拨打invalidate()

另外,我认为这种方法既麻烦又不必要。相反,您可以使用ImageView

祝你好运!