1

我目前正在学习如何为 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);
    }
}
4

3 回答 3

1

尝试创建thread, which sleeps for certain interval of time,然后将值递增 1 直到 9。然后使用Handler to update the UI.

你也可以使用AsyncTask

于 2012-06-17T03:26:47.280 回答
1

一种方法是创建一个可更新视图的可运行文件。这仍将在 UI 线程上更新,但在后台等待。下面的代码中可能有错误,但它应该运行与小的调整..

阻止对您的活动的任何系统调用都不好,因为您正在阻止 UI 线程。您的应用程序将被强制关闭,并显示应用程序无响应消息。这是另一个很好的例子

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);
    }
}
于 2012-06-17T14:36:57.940 回答
0

对 main() 的调用阻止了 UI,因此在调用完成之前它不能显示任何数字。

于 2012-06-17T06:36:16.607 回答