Android 更新UI的方法匯總_Android

來源:互聯網
上載者:User

1、Activity的 runOnUiThread

textView = (TextView) findViewById( R.id.tv );new Thread(new Runnable() {@Overridepublic void run() {runOnUiThread(new Runnable() {@Overridepublic void run() {textView.setText( "更新UI了");}});}}).start();

android Activity runOnUiThread() 方法使用

2、Handler sendEmptyMessage()

package lib.com.myapplication;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends AppCompatActivity {private TextView textView ;Handler handler = new Handler( ) {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);textView.setText( "Ui更新了");}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById( R.id.tv );new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep( 2000 );} catch (InterruptedException e) {e.printStackTrace();}handler.sendEmptyMessage( 2 ) ;}}).start();}}

3、Handler post()

package lib.com.myapplication;import android.os.Bundle;import android.os.Handler;import android.support.v7.app.AppCompatActivity;import android.widget.TextView;public class MainActivity extends AppCompatActivity {private TextView textView ;Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById( R.id.tv );new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep( 2000 );} catch (InterruptedException e) {e.printStackTrace();}handler.post(new Runnable() {@Overridepublic void run() {textView.setText( "Ui更新了");}}) ;}}).start();}}

4、view Post() 

textView = (TextView) findViewById( R.id.tv );new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep( 2000 );} catch (InterruptedException e) {e.printStackTrace();}textView.post(new Runnable() {@Overridepublic void run() {textView.setText( "Ui更新了");}}) ;}}).start();

總結:

1、其實上面的四種方式都可歸結於一種方式:handler 用於Android線程之間的通訊。

2、為什麼android要求只能在UI線程進行UI操作? 主要還是為了避免多線程造成的並發的問題。在單線程操作UI是安全的。

以上所述是 給大家介紹的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.