I want to make an ImageButton rotate when the device orientation changes. It should rotate for 90, 180, 270 and 360 angles and its relative layout should remain steady so only the buttons move. How can this be done? I've done some research but found nothing that could help me.
How to rotate buttons when orientation changes without rotating the layout?
Asked Answered
You have to break the task to the pieces: 1 stop recreation of Activity on rotation. 2. Catching the rotation. 3. Rotating of the View.... Every of this pieces has already an answer, here on SO... It is hard to believe that you didn't find anything... –
Wattmeter
I didn't know how to divide my question into those pieces. I am a newie to Android and Java. I still have a problem because my activity orientation is fixed and I have to detect the orientation with the accelerometer and have no idea how to do it. –
Ingham
You can detect an orientation change by Overriding onConfigurationChanged()
like this:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//call your rotate method here
}
Then once you detect the orientation change event, you can perform an animated rotation on a Button like this:
public void rotateView(View view) {
Button button = (Button) view.findViewById(R.id.some_button);
RotateAnimation rotateAnimation = new RotateAnimation(0, 360);
rotateAnimation.setDuration(2000);
button.startAnimation(rotateAnimation);
}
You can set the starting and ending angle in the constructor of RotateAnimation
, then set the duration for how long the animation should take (in milliseconds). Then you simply call startAnimation()
on the view you want to animate.
Thank you, @drschultz, your answer is great, the problem is my activity orientation is fixed and onConfigurationChanged always give the same result. I'd have said it if I knew how to approach this issue. Any idea on how to detect orientation with the axis x and y with the SensorEventListener? –
Ingham
If your display orientation is locked and cannot be rotated, then unfortunately you'll need to calculate your own rotation values using sensor data. That is where things get quite complex. You can read about Android Sensors in the docs here, and to see some code examples, you can find some good answers on Stack Overflow like this question here. But I would open a new question if you still need help with the sensor stuff. –
Vasta
As for this question, I would kindly ask that you accept my answer since it does answer your original question (and may help others in the future with a similar question). Then, you can open a new question if you need help regarding how to implement sensor data. –
Vasta
it animates then returns to the previous orientation with this. –
Jarlathus
using this, ` super.onConfigurationChanged(newConfig);`, only does what it used to,a nd not using it crashes the app(atleast on kitkat) –
Hallie
© 2022 - 2024 — McMap. All rights reserved.