如何在android中的另一个线程中运行任务时更新UI?

时间:2016-10-12 11:16:03

标签: android

我尝试使用文本视图更新我的用户界面我所做的是无限期地运行while循环并让线程休眠一秒钟..

 int i;
    while(true)
    {
        Thread.Sleep(1000);
        textView.setText(updateTime);
    }

3 个答案:

答案 0 :(得分:1)

  

使用runOnUiThread并使用try catch for Thread.sleep(1000)

进行环绕
int i;
    while(true)
    {
        try {
            Thread.sleep(1000);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    textView.setText(updateTime);
                }
            });
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

答案 1 :(得分:1)

试试这个arnab ......

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView textView = (TextView) findViewById(R.id.displayid);
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            bundle = msg.getData();
            textView.setText(bundle.getString("mKey"));
        }
    };

}
public void press(View v) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    try {
                        wait(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    bundle = new Bundle();
                    message = handler.obtainMessage();
                    simpleDateFormat = new SimpleDateFormat("hh:mm:ss YYYY/mm/dd", Locale.US);
                    date = simpleDateFormat.format(new Date());
                    bundle.putString("mKey", date);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            }

        }
    }).start();
}

答案 2 :(得分:0)

尝试runOnUiThread:

runOnUiThread(new Runnable() {

    @Override
    public void run() {
        textView.setText(updateTime);
    }
});