理解 Canvas.onDraw() 的概念有问题吗?
我编写了以下简单的代码来查看渲染的行为。在此代码中,我正在更改屏幕的颜色。
我不明白的是,为什么这段代码会永远运行?我没有使用无限循环,但这段代码将永远运行!
请告诉我原因。谢谢
package kamalan.com.androidbasicstarter;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class RenderViewTest extends Activity{
class RenderView extends View{
Random rand = new Random();
public RenderView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas){
canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
invalidate();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new RenderView(this));
}
}
I have written following simple code to see the behavior of rendering. In this code i'm changing the color of screen.
The thing that I can't understand is, why this code is running for ever? I didn't use unlimited loop but this code will run for ever!
Please tell me the reason. Thanks
package kamalan.com.androidbasicstarter;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class RenderViewTest extends Activity{
class RenderView extends View{
Random rand = new Random();
public RenderView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas){
canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
invalidate();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new RenderView(this));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
invalidate
导致重绘。从onDraw
调用它通常(总是?)是个坏主意,因为它会导致立即再次调用onDraw
。这就是你所看到的。invalidate
causes a redraw. It's usually (always?) a bad idea to call that fromonDraw
, because it will causeonDraw
to be called again immediately. Which is what you are seeing.