Android开发更新UI的几种方式

1、runOnUiThread

2、handler post

3、handler sendmessage

4、view post

 xml布局文件:        

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.example.handlerui.MainActivity" >

  <TextView
  android:id="@+id/textView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="50sp"
  android:text="@string/hello_world" />

  </RelativeLayout>

  MainActivity.java

  

package com.example.handlerui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
//textView.setText("OK"); //使用handler2更新UI的时候去掉注释
      };

	};

	private void handler1(){
handler.post(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
textView.setText("OK");
}
});
} private void handler2(){
handler.sendEmptyMessage(1);
} private void updateUi(){
runOnUiThread(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
textView.setText("OK");
}
});
} private void viewUI(){
textView.post(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
textView.setText("OK");
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
new Thread(){
public void run() {
try {
Thread.sleep(2000);
//handler1();
handler2();
//updateUi();
//viewUI();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} };
}.start();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

  

上一篇:14_Android中Service的使用,关于广播接收者的说明


下一篇:Fiddler手机抓包设置