开发者

Android loop problem

I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?

> package com.and开发者_如何转开发roid.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
> 
> 
> import android.view.View; import
> android.view.Window;
> 
> public class Android extends Activity
> { int x,y=10;
> 
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
> 
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
> 
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
> 
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }


Your onDraw() method never returns. It needs to. Does your app Force Close after a few seconds? You're going to have to post a message to the UI thread to redraw after 30 milliseconds instead of looping within onDraw(). Off the top of my head, try this instead:

class Panel extends View {
  public Panel(Context context) {
    super(context);
  }

  int x = 0;
  int y = 0;
  Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

  @Override public void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(_scratch, x, y, null);
    x+=2; y+=2;
    this.postInvalidateDelayed(30);
  }
}

Of course you need to add some code to stop looping once the icon has gone off the edge.


I'm amateur Android Dev too, and I think I recall reading that its a bad habit to call Thread.Sleep() as a workaround. But I could be wrong.


onDraw is intended for rendering the display - once. It's probably a bad idea to try and do this loop in onDraw.

Rather than using a loop, you might want to try using animation. Do a google search for "Android animate tutorial" or something similar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜