I'm emulating a Frame Animation; I have it all working spare one issue.
I have a for loop in which, on every iteration, it changes the Image of an ImageView after a delay.
for(int i = 1; i <13; i++){
if (stop== false){
String imgName = "b"+ Integer.toString(i);
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
Handler handlerTimer = new Handler();
handlerTimer.postDelayed(new Runnable(){
public void run() {
view.setImageDrawable((getResources().getDrawable(id)));
}}, 300);
}
}
The issue is that run() doesn't refresh on every iteration; it only works once.
How can I refresh or make a new run()?
I'm open to any other way to do this.
Any advice would be appreciated.
Step #1: Define the Runnable
as a data member of your activity (or wherever this code resides)
Step #2: Dump the Handler
, as you don't need it -- postDelayed()
is implemented on View
as well
Step #3: Create a helper method that does the postDelayed()
call -- I'll refer to that method as foo()
here -- and call foo()
where you right not call postDelayed()
Step #4: In run()
of the Runnable
, call foo()
again to reschedule the Runnable
for another delay period
Give this a try, if it doesnt work then ill try somthing else:
for(int i = 1; i <13; i++)
{
if (stop== false)
{
String imgName = "b"+ Integer.toString(i);
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
Handler handlerTimer = new Handler();
handlerTimer.postDelayed(new Runnable(){
public void run() {
view.setImageDrawable((getResources().getDrawable(id)));
view.invalidate();
}}, 300);
}
}
invalidate() should cause your view to be repainted and you should get the desired effect. Hope this helps!
This is the Thread example:
public class Main implements Runnable
{
public Main()
{
Thread thread = new Thread(this);
thread.start();
//new Thread starts at run()
}
public void run()
{
String imgName = "b"+ Integer.toString(i);
id = getResources().getIdentifier(imgName, "drawable", getPackageName());
try
{
for(int i = 1; i <13&!stop; i++)
{
view.setImageDrawable((getResources().getDrawable(id)));
Thread.sleep(300);
}
}catch(Exception e){e.printStackTrace();}
}
public static void main(String args[]){new Main();}
}
if you need anything else at all, just let me know!