这是我的代码
try {
final double calcResult = CalcUtils.evaluate(textViewOutputScreen.getText().toString());
textViewOutputScreen.setText(Double.toString(calcResult)); //setting text to text view
new voices().voice(calcResult); //this method takes about 5-10 seconds to execute
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
textViewOutputScreen.setText("0");
}
我在第二行中设置为TextView
的文本在5-10秒后在屏幕上更新,即在方法new voices()之后更新语音(calcResult);已完成执行。
我在方法中保留了这样的延迟
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
我想在调用方法之前刷新文本视图我该怎么办?
我搜索了类似的问题,但没有一个能为我工作。
答案 0 :(得分:0)
您似乎正在main
主题中执行代码,TextView.setText(...)
最后位于event queue
,因此new Voices().voice()
之后会更新代码完成执行。
您可以尝试通过以下方式更新TextView
中的UI Thread
:
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
textViewOutputScreen.setText(Double.toString(calcResult));
}
});
一个更好的解决方案当然是在后台运行长时间运行的任务......
答案 1 :(得分:0)
在运行new voices().voice(calcResult);
textViewOutputScreen.invalidate();
如果这样做不起作用,你可以尝试将重负荷放在AsyncTask
它在后台执行,基于Java Thread。您可以在当前AsyncTask
/ class
Activity
作为嵌套类
private class VoiceTask extends AsyncTask<Double, Void, Void> {
protected void doInBackground(Double... stuff) {
//Do whatever voice does!
double calcResult = stuff[0];
new voices().voice(calcResult);
}
protected void onPostExecute(Long result) {
//Is called when you are done, if you want to send stuff here
//you need to change this example, see the link below
//Not necessary to override (If I remember correctly)
}
}
接下来,您只需创建一个AsyncTask并使用您的参数执行它。该值将在doInBackground
中提供。
try {
final double calcResult = CalcUtils.evaluate(textViewOutputScreen.getText().toString());
textViewOutputScreen.setText(Double.toString(calcResult)); //setting text to text view
new VoiceTask().execute(calcResult); //CHANGED LINE
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
textViewOutputScreen.setText("0");
}