Android 在子線程中更新UI的幾種方法

來源:互聯網
上載者:User

標籤:

第一種:

new Handler(context.getMainLooper()).post(new Runnable() {@Overridepublic void run() {// 在這裡運行你要想的操作 比方直接在這裡更新ui或者調用回調在 在回調中更新ui}});

context是你傳過來的context對象


另外一種:

// 假設當前線程是UI線程,那麼行動是馬上運行。假設當前線程不是UI線程,操作是公布到事件隊列的UI線程// 由於runOnUiThread是Activity中的方法,Context是它的父類,所以要轉換成Activity對象才幹使用((Activity) context).runOnUiThread(new Runnable() {@Overridepublic void run() {// 在這裡運行你要想的操作 比方直接在這裡更新ui或者調用回調在 在回調中更新ui}});
第三種:

第三種是使用Handler的方法,往Handler中發送一個訊息,然後當Handler接收到你發送過來的訊息,再在Handler運行對應的操作
這是接收訊息啟動並執行代碼:

private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 1:button1.setText("點擊安裝");down = 1;break;case 2:down = 2;button1.setText("開啟");break;}}};

這是發送訊息的代碼:

// 往handler發送一條訊息 更改button的text屬性Message message = handler.obtainMessage();message.what = 1;handler.sendMessage(message);


Android 在子線程中更新UI的幾種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.