how to rotate button about its center in android
-
12-11-2019 - |
Question
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;
}
}
}
OTHER TIPS
Easier...
http://developer.android.com/reference/android/view/animation/RotateAnimation.html#RotateAnimation(float, float, int, float, int, float)
new RotateAnimation(_oldAngle, _newAngle, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
use
RotateAnimation(float fromDegrees, float toDegrees, float pivotX, float pivotY)
pivotX, pivotY - coordinates of button center. and it looks like your angles are the same
The simplest solution deserves to be mentioned:
button.setRotation( angle );
Put that in your onClick
method. For example:
public void onClick( View v ) { v.setRotation( v.getRotation() + 30f ); }
See the View API.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow