Reputation: 1203
I am making an application in which i am changing the the layout background continually like flipping the background, I am implementing the background change using Activity.runOnUiThread()
function since it is a UI function and waiting for 2 seconds using Thread().sleep()
but the application only shows the layout color I mentioned in the end.
package com.tutorial.flasher;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
//import android.os.SystemClock;
//import android.os.SystemClock;
import android.widget.LinearLayout;
public class flasher extends Activity {
/** Called when the activity is first created. */
LinearLayout llaLayout;
Thread th = new Thread("ThreadOne");
Activity _activity = new Activity();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
llaLayout = (LinearLayout)findViewById(R.id.layo);
Thread t1 = new Thread(new Runnable() {
public void run() {
try
{
Thread.sleep(2000);
}
catch (Exception e) {
// TODO: handle exception
}
}
});
t1.start();
t1.run();
t1.stop();
_activity.runOnUiThread(new Runnable(){
public void run(){
llaLayout.setBackgroundColor(Color.parseColor("#00FF00"));
}
});
//t1.currentThread();
t1.start();
t1.run();
t1.stop();
_activity.runOnUiThread(new Runnable(){
public void run(){
//Color BLUE of layout
llaLayout.setBackgroundColor(Color.parseColor("#0000FF"));
}
});
}
}
Both the UI changes and Thread staring would be happening in a loop(which is not shown) but still the application is changing the layout color only once. Thanks, Sid
Upvotes: 0
Views: 4189
Reputation: 1576
new
Activity, Activity is created by Android system. Thread.start
will start the thread, there is no need to call Thread.run
.Activity.runOnUiThread
maybe not the best way to archive this, try Handler
. Here is sample code:
public class BroadcastActivity extends Activity {
public static final int CHANGE_BGCOLOR = 1;
private LinearLayout llaLayout;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
String color = (String) msg.obj;
llaLayout.setBackgroundColor(Color.parseColor(color));
String nextColor = ""; // Next background color;
Message m = obtainMessage(CHANGE_BGCOLOR, nextColor);
sendMessageDelayed(m, 200);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
llaLayout = (LinearLayout)findViewById(R.id.layo);
String nextColor = ""; // Next background color;
Message m = handler.obtainMessage(CHANGE_BGCOLOR, nextColor);
handler.sendMessageDelayed(m, 200);
}
}
Upvotes: 3