Reputation: 61
I have a class that is supposed to show a screen in white and fade through a lot a colors.
public class SecondActivity extends Activity implements Runnable {
protected PowerManager.WakeLock mWakeLock;
boolean isrunning = true;
int red = 0, blue = 0, green = 0;
@Override
public void onCreate(Bundle savedInstanceState) .... etc
TextView btnstart = (TextView) findViewById(R.id.btnstart);
btnstart.setTypeface(font1);
btnstart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.button);
try {
mediaPlayer.start();
mediaPlayer.setLooping(false);
} catch (Exception e) {
e.printStackTrace();
}
{
run();
}
;
}
});
then my runnable
@Override
public void run() {
while (isrunning) {
try {
red = red + 1;
blue = blue + 2;
green = green + 3;
if (green > 240){
red = 0;
blue = 0;
green = 0;
}
LinearLayout colorchanger = (LinearLayout) findViewById(R.id.colorchange);
colorchanger.setBackgroundColor(Color.argb(255, red, blue,
green));
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have the following problem when I press the button the app force closes. If I take out the " while(isrunning)" and replace it with if (isrunning ) it all works but I want the color to keep changing after I click the button.
I´m sure I´m doing something wrong....
Perhaps doing it with a layout is not the best way and I have to do it with a rectangle( size the screen )? and change the color during the onDraw?
Upvotes: 0
Views: 291
Reputation: 7915
Handlers are well suited for this.
// Initialize your handler:
Handler h = new Handler();
// Start fading:
h.postDelayed(color_fade, 0);
// Set up your runnable:
private Runnable color_fade = new Runnable(){
public void run(){
/*
* Do your color and layout changes here.
*/
h.postDelayed(this, 100); // loop with 100 ms delay.
}
};
Upvotes: 2