0

Ok, I have got following code from https://github.com/hongyangAndroid/Android-CircleMenu . Here, from print trace, I came to find that constructor is only invoked once, whereas run() method is recursively called till some condition.

My question is, why only run() method is recursively called from postDelayed(), why not constructor? and how variable anglePerSecond retains the value ? I want to understand it's flow. Thanks you.

  //Automatic scrolling tasks
  private class AutoFlingRunnable implements Runnable{
    private float anglePerSecond;
    public AutoFlingRunnable(float velocity){
        this.anglePerSecond = velocity;
    }
    public void run(){
        if((int)Math.abs(anglePerSecond) < 20){
            isFling = false;
            return;
        }
        isFling = true;

        //anglePerSecond/30 in order to avoid rolling too fast
        mStartAngle += (anglePerSecond/30);
        //Gradually reduce this value
        anglePerSecond /= 1.0666F;
        postDelayed(this, 30);
        //gradually reduce this value
        requestLayout(); //re-layout views
    }
}
Binod Lama
  • 226
  • 5
  • 24

1 Answers1

1

When you want to update the textView in the Activity, for example , a textView with the countdowntimer, you normally update it with the following code

    final int time = 50;
    final TextView textView = new TextView(this);
    textView.postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            textView.setText(String.format("Remaing Time : %d s", time));
        }
        /*
         * Update it after 1 second
         * 1秒後更新
         */
    },1000);

If you understand the above code, then try to understand the following

    textView.postDelayed(new Runnable() {


        @Override
        public void run() {
            // TODO Auto-generated method stub
            textView.setText(String.format("Remaing Time : %d s", time));
            /*
             * Update it after 1 second
             * 1秒後更新
             */
            textView.postDelayed(this, 1000);
        }
        /*
         * Update it after 1 second
         * 1秒後更新
         */
    },1000);

Actually, it is the same progress inside the library you provided. It is dosing sth like that.

1.call AutoFlingRunnable consturctor to create

2.Method call in line 366

3.run the AutoFlingRunnable run() method

4.run the same runnable run() method after 0.03 second in line 574

5.back to step 3

Long Ranger
  • 5,888
  • 8
  • 43
  • 72