1

这是我的代码:

public class MainActivity extends Activity {
    private TextView view;
    private Handler handler = new Handler();

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

        view = (TextView) findViewById(R.id.view);
        view.setText("how are you");

        handler.post(r);

        System.out.println("oncreate");
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        System.out.println("onstart");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    Runnable r = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
}

activity_main.xml中,我采用的是LinearLayout,里面只有一个TextView。运行程序后,10秒后屏幕上会出现“你好吗”的文字。但是文本字符串“oncreate”和“onstart”可以立即显示在logcat中。这怎么可能发生?在我看来,所有的文本字符串应该在程序运行后的 10 秒后显示出来。

4

1 回答 1

0

简单的方法是:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (TextView) findViewById(R.id.view);
System.out.println("oncreate");
new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
         }
}).start();
    view.setText("how are you");

}

此代码将立即在 logcat 上打印“onstart”和“oncreate”,接下来 10 秒将在 textview 上设置文本...

于 2013-02-18T14:24:13.563 回答