每当我点击一个选项时,for循环将首先出现,在for循环结束后,将设置按钮文本。为什么在for循环完成之后设置,当它在for循环之前被触发?
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.refresh) {
Button button = (Button) findViewById(R.id.button);
button.setText("Running");
Toast.makeText(MainActivity.this, "We are currently running this function", Toast.LENGTH_SHORT).show();
for (int i = 0; i < 100; i++) {
try {
System.out.println("For is running" + i);
} catch (NullPointerException e) {
//Don't do shit :)
}
}
}
}
答案 0 :(得分:1)
您的问题是您在循环中停止UI线程。它将文本设置为按钮对象级别,但在此之前可以反映到用户界面。如果要执行一些需要花费大量时间的代码,则应始终使用后台活动。有关示例,请参阅“https://developer.android.com/reference/android/os/AsyncTask.html”。
答案 1 :(得分:0)
1)首先,方法public boolean onOptionsItemSelected(MenuItem item)等待直到你发回一个布尔值。在你返回真实之前我不会显示你的按钮。
2)其次,UI线程上的sleep()非常糟糕。而是尝试runOnUlThred():
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.refresh)
{
Button button = (Button) findViewById(R.id.button);
button.setText("Running");
Toast.makeText(MainActivity.this, "We are currently running this function", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable()
{
public void run()
{
for (int i = 0; i < 100; i++) {
try {
System.out.println("For is running" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (NullPointerException e) {
//Don't do shit :)
}
}
}
}
return true;
}
else return super.onOptionsItemSelected(item);
}