Thursday, 19 September 2013

How to get a Random Non Final variable inside a runnable ? -Android

How to get a Random Non Final variable inside a runnable ? -Android

Can't explain this before showing the code, so :
final int randomcolor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
final Runnable updater = new Runnable() {
@Override
public void run() {
relativeLayout.setBackgroundColor(randomcolor);
handler.postDelayed(this, 25);
}
}
};
Above I have a runnable named Updater... and below I'm starting it up on a
button click..
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
handler.postDelayed(updater,2000 );
}
});
(I've cut out most of my code so this may not make sense why I want to do
this. The above will create an infinite loop as the runnable is stuck with
no way out... Just assume that I can get out of it.)
Explaination of the code
ALL this is in Oncreate()... So, on a button click I'm starting up a
Runnable after a delay of two seconds... and then, after every 25
millisecond gap the same runnable is running again and again till the end
of time( Like I said, ignore this last point.)
You will see I'm doing only one thing in the runnable, changing the
background color of the relative layout.
Important, what I want is that after every 25 milliseconds, ie., everytime
the runnable runs, It should change the relative Layout's background color
to something random. It will probably look like a drunkard flashy epilepsy
inducing app... Leave the reason to me (again)
The problem is, the handler can't take a non-final runnable... and a
random variable for every run can't be final and final and non-final don't
work together. (read it again)
So, I need a new Color integer everytime the runnable runs...So that every
time it runs, it changes the background color to something different and
random.
I feel the solution is quite simple, but I can't seem to in it down..
Any ideas people? How I might go about doing this ?

No comments:

Post a Comment