更新布局类

时间:2013-08-16 20:35:55

标签: android layout runnable layout-inflater

我的问题是,我有一个由Layout调用的Inflater类,我想从这个类中运行一个方法来每隔几秒更新一次图片。

我想用处理程序和run()方法执行此操作,但问题是,当我与屏幕交互时(单击我的唯一按钮),图片才会自动更新。

你知道我做错了吗?

这是我的GameLayout课程:

package de.undeadleech.frogjump;

public class GameLayout extends View implements Runnable
{
private Sprite sprite;
private Bitmap bmp;
private Handler handler = new Handler();

public GameLayout(Context context) 
{
    super(context);
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.froschanimation);
    sprite = new Sprite(bmp, 0, 0, 400, 100, 5, 4);
    handler.postDelayed(this, 0);
}

@Override
protected void onDraw(Canvas canvas)
{
    sprite.draw(canvas);
}

public void update(long currentTimeMillis) 
{
    sprite.update(currentTimeMillis);
}

@Override
public void run()
{
    sprite.update(System.currentTimeMillis());
    handler.postDelayed(this,  0);
}
}

编辑:

这是我的Sprite课,因为你想看到它:

package de.undeadleech.frogjump;



public class Sprite 
{   
//private static final String TAG = Sprite.class.getSimpleName();

private Bitmap bitmap;      // the animation sequence
private Rect sourceRect;    // the rectangle to be drawn from the animation bitmap
private int frameNr;        // number of frames in animation
private int currentFrame;   // the current frame
private long frameTicker;   // the time of the last frame update
private int framePeriod;    // milliseconds between each frame (1000/fps)

private int spriteWidth;    // the width of the sprite to calculate the cut out rectangle
private int spriteHeight;   // the height of the sprite

private int x;              // the X coordinate of the object (top left of the image)
private int y;              // the Y coordinate of the object (top left of the image)

public Sprite(Bitmap bitmap, int x, int y, int width, int height, int fps, int frameCount) 
{
    this.bitmap = bitmap;
    this.x = x;
    this.y = y;
    currentFrame = 0;
    frameNr = frameCount;
    spriteWidth = bitmap.getWidth() / frameCount;
    spriteHeight = bitmap.getHeight();
    sourceRect = new Rect( 0, 0, spriteWidth, spriteHeight);
    framePeriod = 1000 / fps;
    frameTicker = 0l;
}

public void update(long gameTime) 
{
    if (gameTime > frameTicker + framePeriod) 
    {
        frameTicker = gameTime;
        // increment the frame
        currentFrame++;
        if (currentFrame >= frameNr) 
        {
            currentFrame = 0;
        }
    }
    // define the rectangle to cut out sprite
    this.sourceRect.left = currentFrame * spriteWidth;
    this.sourceRect.right = this.sourceRect.left + spriteWidth;
}

public void draw(Canvas canvas) 
{
    // where to draw the sprite
    Rect destRect = new Rect( x, y, x + spriteWidth, y + spriteHeight);
    canvas.drawBitmap(bitmap, sourceRect, destRect, null);
}
}

1 个答案:

答案 0 :(得分:0)

当您需要重新绘制布局时,应该调用Runnable,而不是发布invalidate()。此外,您还应该在Sprite方法中更新onDraw的状态。