Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android for loop not working in main thread

i try to rotate image. i used runnable to rotate image,i wrote for loop and i want to rotate image inside for loop this is a my source

public void rotateimages(final View myView) {
    myHandler = new Handler();
    runnable = new Runnable() {

        @Override
        public void run() {

            double k = 30;

            double speed = Math.PI / k;
            for (alpa = 0; alpa < (Math.PI * 6 + res * 2 * Math.PI / 5); alpa += speed) {

                myView.setRotation((float) (myView.getRotation() - alpa));

                Log.e("alpa values", String.valueOf(alpa));

                k = Math.min(k + 0.2, 240);
                speed = Math.PI / k;
                myHandler.postDelayed(this, 100); 
            }
            // rotateimages();
        }

    };

    myHandler.postDelayed(runnable, 180);
}

when i run my app i can rotate only one time.what is a wrong in my code? if anyone knows solution please help me

like image 724
viviano Avatar asked Nov 21 '25 15:11

viviano


1 Answers

If you want to loop , you need to define this 'runnable' loop again itself edit your code to:

myHandler = new Handler();
count = 0;
public void rotateImage(final View myView, final int size) {


    runnable = new Runnable() {

        @Override
        public void run() {

            count++;
            myView.setRotation(myView.getRotation() + size);
            if(count == 10){
               myHandler.removeCallBack(runnable );
            }
           myHandler.postDelayed(this, 1000); // 1000 means 1 second duration
         }
        };
        myHandler.postDelayed(runnable, 180); // 180 is the delay after new runnable is going to called

}

How to loop itself, that's mean one code line, or one statement call the event again. Some example:

 void nothing(int a){
   if(a> 0)
     nothing(a-1);
   }

and call nothing(10). that's all, and avoid some action like:

void nothing(int a){
       for(int i =0; i< a;i++) 
         nothing(a-1);                //BIG WRONG
       }
 Do you know your solution?
like image 111
kemdo Avatar answered Nov 23 '25 05:11

kemdo