这是我的密码
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 ().voice(CalcResult)完成后进行更新。
我很少有这样的拖延。
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
我想在这个方法被调用之前刷新文本视图,我怎么做呢?
我寻找类似的问题,但没有一个对我有用。
发布于 2016-06-22 11:21:58
在运行new voices().voice(calcResult);
之前尝试使视图无效
textViewOutputScreen.invalidate();
如果这不起作用,你可以试着把沉重的负载放在AsyncTask
上
它在后台执行,并基于Java。可以将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");
}
发布于 2016-06-22 11:20:29
您似乎正在main
线程中执行您的代码,而TextView.setText(...)
被放在event queue
中的最后一个位置,因此在new Voices().voice()
完成执行之后就会得到更新。
您可以尝试通过以下方法从TextView
更新UI Thread
:
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
textViewOutputScreen.setText(Double.toString(calcResult));
}
});
当然,更好的解决办法是在后台执行长期运行的任务.
https://stackoverflow.com/questions/37966292
复制相似问题