1.Handler方式
public class MainActivity extends AppCompatActivity {
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.Textview1);
new Thread(new Runnable() {
@Override
public void run() {
Message msg=new Message();
msg.obj="泥吼啊!";
handler.sendMessage(msg);
}
}).start();
}
//Handler要写在主线程内
Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
String text= (String) msg.obj;
textView1.setText(text);
}
};
}
2.不晓得怎么说
public class MainActivity extends AppCompatActivity {
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.Textview1);
handler.postDelayed(runnable,ms);
}
private long ms=1000;
Handler handler =new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
textView1.setText("猴赛雷!");
}
};
}
3.runOnUiThread
public class MainActivity extends AppCompatActivity {
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.Textview1);
runOnUiThread(
new Thread(new Runnable() {
@Override
public void run() {
textView1.setText("鲨雕看这里!");
}
})
);
}
}
4.handler.post
public class MainActivity extends AppCompatActivity {
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.Textview1);
handler.post(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mTextView.setText("子线程通过post方法更新后的UI");
}
});
}
}
5.
public class MainActivity extends AppCompatActivity {
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.Textview1);
textView1.post(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mTextView.setText("子线程通过view.post方法更新后的UI");
}
});
}
}
来源同上