我是 Android 新手,我正在尝试使用 UI-Thread,所以我编写了一个简单的测试活动。但我想我误解了一些东西,因为点击按钮 - 应用程序不再响应
public class TestActivity extends Activity { Button btn; int i = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runThread(); } }); } private void runThread(){ runOnUiThread (new Thread(new Runnable() { public void run() { while(i++ < 1000){ btn.setText("#"+i); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } })); } }
以下是更正的runThread功能片段。
runThread
private void runThread() { new Thread() { public void run() { while (i++ < 1000) { try { runOnUiThread(new Runnable() { @Override public void run() { btn.setText("#" + i); } }); Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); }