【发布时间】:2014-09-12 21:07:57
【问题描述】:
我正在使用 Android (Java),我想要的是获取一个类,并从中创建 3 个实例,但将一些变量设置为随机。
public class MainActivity extends Activity{
Player ourView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourView = new Player(this);
setContentView(ourView);
}
protected void onPause() {
super.onPause();
ourView.pause();
}
protected void onResume() {
super.onResume();
ourView.resume();
}
}
另一个类...
public class Player extends SurfaceView implements Runnable {
Canvas canvas = new Canvas();
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
public Player(Context context) {
super(context);
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
}
public void pause() {
isRunning = false;
while(true){
try{
ourThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
}
public void run() {
while(isRunning) {
if(!ourHolder.getSurface().isValid())
continue;
canvas = ourHolder.lockCanvas();
canvas.drawRGB(30, 30, 200);
Enemy[] enemy = new Enemy[3];
for(int i = 0; i<enemy.length; i++){
enemy[i] = new Enemy();
enemy[i].draw();
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
还有“敌人”类:
public class Enemy{
Canvas canvas = new Canvas();
float x = (float) (Math.random()*200);
float y = (float) (Math.random()*200);
public void draw(){
Bitmap bitmap = (Bitmap) BitmapFactory.decodeResource(getContext(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, x, y, null);
}
}
我可以看到创建了 3 个位图,这很酷。但它们不会静止不动,就像即使条件不再满足,for 循环也不会停止。
我之前问过这个问题,但我找不到任何答案。希望你能帮助我,谢谢。
【问题讨论】:
-
“为什么我不能乘以一个对象”。你这是什么意思?
-
哪个'for'循环永远不满足?
-
我认为他们的意思是“while”循环?
-
当您说“条件不再满足”时,您的意思是
isRunning?看起来只有在应用程序暂停时才设置为 false。这是预期的行为吗?你确定onPause()被叫到了吗?您可能想尝试使用Log.d来确保它被调用。还可以尝试将volatile添加到isRunning的声明中。 -
我的意思是“for”循环。因为当 int "i" 的值达到 3 时,循环应该停止。