好的,我正在制作一个基本的应用程序,其中有一个马铃薯的图片,通过应用程序编辑元素的填充来增长和缩小。我是Threads的新手,我肯定在睡眠/等待时出错了。
这是我的代码;这是相对自我解释的:
package com.Potato.growingpotato;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
public class GrowScreen extends Activity {
private Thread thread;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grow_screen);
thread = new Thread() {
public void run() {
growPotato();
handler.postDelayed(this, 1000);
}
};
thread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_grow_screen, menu);
return true;
}
@Override
public void onResume(){
super.onResume();
handler.removeCallbacks(thread);
handler.postDelayed(thread, 0);
}
public void HarvestPotato(View view) {
ImageView ThePicture = (ImageView) findViewById(R.id.imageView);
ThePicture.setPadding(150,150,150,150);
thread.start();
}
public void NapTime(int Time) { //Try to make the application sleep for 'Time'
try {
Thread.sleep(Time);
} catch (Exception e) {
e.getLocalizedMessage();
}
}
public void growPotato() { //Fancy Padding manipulation
long base = System.currentTimeMillis();
long WorkingNum = 0;
ImageView PotatoPicture = (ImageView) findViewById(R.id.imageView);
do {
NapTime(100);
WorkingNum = 150 - ((System.currentTimeMillis() - base)/100);
PotatoPicture.setPadding((int)WorkingNum, (int)WorkingNum, (int)WorkingNum, (int)WorkingNum);
} while(WorkingNum > 5 );
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(thread);
}
}
应用程序在启动后冻结,它是一个白色屏幕。最终,图片以全尺寸弹出,按钮也是如此;按下按钮时,它会完全冻结