我目前正在学习如何为 Android 移动设备开发应用程序。
我编写了一个测试应用程序以在设备屏幕上显示数字 0-9。我创建了一个简单的函数来延迟号码更改。
但是,在运行应用程序时,只会显示最终数字。在显示最终数字之前也有延迟。我假设暂停的长度是我定义的延迟乘以要显示的位数。
如何创建延迟更改数字的应用程序?
public class AndroidProjectActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Main();
}
void Delay(int Seconds){
long Time = 0;
Time = System.currentTimeMillis();
while(System.currentTimeMillis() < Time+(Seconds*1000));
}
void Main() {
String ConvertedInt;
TextView tv = new TextView(this);
setContentView(tv);
for(int NewInt = 0; NewInt!= 9; NewInt++){
ConvertedInt = Character.toString((char)(NewInt+48));
tv.setText(ConvertedInt);
Delay(5);
}
}
最佳答案
执行此操作的一种方法是创建一个可更新 View 的可运行对象。这仍然会在 UI 线程上更新,但会在后台等待。下面的代码可能有错误,但它应该可以通过一些小的调整运行..
阻止对您的 Activity 的任何系统调用是不好的,因为您正在阻止 UI 线程。您的应用程序将被强制关闭,并显示应用程序未响应消息。这里还有一个好example .
public class AndroidProjectActivity extends Activity {
private Handler mHandler;
private TextView mTextView;
private Runnable mCountUpdater = new Runnable() {
private int mCount = 0;
run() {
if(mCount > 9)
return;
mTextView.setText(String.valueOF(mCount+48));
mCount++;
// Reschedule ourselves.
mHandler.postDelayed(this, 5000);
}
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Cleaner to load a view from a layout..
TextView tv = new TextView(this);
setContentView(tv);
mTextView = tv;
// Create handler on UI thread.
mHandler = new Handler();
mHandler.post(mCountUpdater);
}
}
关于java - 如何在 Android 上暂停/延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068257/