I want to create a subclass of linear layout,and it’s background color must be change Black or White.I wrote this code:
public class MyLayout extends LinearLayout implements Runnable {
int color = 0xFFFFFFFF;
public MyLayout(Context context) {
super(context);
Thread t = new Thread(this);
t.start();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
if(color == 0xFF000000){
color = 0xFFFFFFFF;
}else{
color = 0xFF000000;
}
this.setBackgroundColor(color);
postInvalidate();
System.out.println("Color >> " + color);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And then I set it as ContentView of my Activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyLayout(this));
}
After running App in Emulator,run method of MyLayout executes without any exception,but backgroung color is always Black.What I’m doing wrong?
In following up @Hisham Muneer,I send instance of my Activity to my class and it works.
runOnUiThreadis a method inActivityclass.This is finall code: