1

我知道您只能从 UI 线程更改 tTxtViews 中的文本,但我似乎无法找到一种方法来处理它。

我将介绍更多细节:我正在尝试使用 TextView 来显示经过的时间,但我无法在线程中执行此操作,或者无法在不断调用的方法中执行此操作。你能帮我解决这个问题吗?因为我几乎没有想法。

谢谢。

4

2 回答 2

2

用这个

new Thread(new Runnable() {

    @Override
    public void run() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // Do what you want.
            }          
        });
   }         
}).start();

或使用Handler

Runnable r = new Runnable() {

    @Override
    public void run() {
        // Do what you want.
    }
};
Handler mHandler = new Handler();
mHandler.post(r);
于 2012-12-15T23:54:09.000 回答
2
        public class MainActivity extends Activity {

            protected static final long TIMER_DELAY = 100;
            private TextView tv;
            protected Handler handler;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                tv = (TextView)findViewById(R.id.helloWorld);
                handler = new Handler();
                handler.post(timerTask);


            }

            private Runnable timerTask = new Runnable() {
                public void run() {
                    Calendar now = Calendar.getInstance();

                    //format date time
                    tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)));

                    //run again with delay
                    handler.postDelayed(timerTask, TIMER_DELAY);
                }
            };


        }

忘记加了,不好意思。不要忘记这样做:

@Override
    public void onPause() {

        if (handler != null)
            handler.removeCallbacks(timerTask);

        super.onPause();
}

如果你想要恢复应用程序试试这个

@Override
    public void onResume() {
        super.onResume();

        if (handler != null)
            handler.post(timerTask);
}
于 2012-12-16T00:11:38.460 回答