I am totaly new to android and just want to know if it is any working and possible way to update the UI outside the main thread. Just from my code I have listed below I know that from this code; It is not possible at all. But, the thing is I just want to update the UI using another thread. Please help me thanks in advance!
package com.example.app;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button b;
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
Thread t=new Thread(new MyThread());
t.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;
}
private class MyThread implements Runnable{
Random randomGenerator = new Random();
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.getStackTrace();
}
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…