Search code examples
androidandroid-orientation

how to rotate button about its center in android


hi in my app i am trying to rotate button about its centre but it is not rotating based on its center instead it is moving from its position.below is my code please help me how to solve that issue.

 public class example extends Activity {
float newAngle,oldAngle=0;


int flag=0;
int n=340;
 RotateAnimation animation,animation1;

    Button arrow;
    Button left,right;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     arrow=(Button)findViewById(R.id.img);
     left=(Button)findViewById(R.id.left);
     right=(Button)findViewById(R.id.right);
    final int width = arrow.getWidth();
    final int height = arrow.getHeight();      

     left.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(flag>=0)
            {
                   newAngle = oldAngle+ 30;

                    oldAngle=newAngle;
            }
            flag++;
            Log.i("flag",""+flag);
             animation = new RotateAnimation(oldAngle, newAngle);
             animation.setFillAfter(true);
             animation.setDuration(200);
             arrow.startAnimation(animation);
        }
    });
     }
       }

Solution

  • full example:

     public class MyActivity extends Activity implements View.OnClickListener {
    
        private ImageView _image;
        private float _newAngle, _oldAngle;
    
    
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(this);
            _image = (ImageView) findViewById(R.id.image);
        }
    
        public void onClick(View view) {
            if (view.getId() == R.id.button) {
                _newAngle = _oldAngle + 30;
    
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) _image.getLayoutParams();
                int centerX = layoutParams.leftMargin + (_image.getWidth()/2);
                int centerY = layoutParams.topMargin + (_image.getHeight()/2);
                RotateAnimation animation = new RotateAnimation(_oldAngle, _newAngle, centerX, centerY);
                animation.setDuration(0);
                animation.setRepeatCount(0);
                animation.setFillAfter(true);
                _image.startAnimation(animation);
    
                _oldAngle = _newAngle;
            }
        }
    }