Advertisement
codeuniv

Android - auto-change ImageView orientation

Nov 1st, 2019
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. https://stackoverflow.com/questions/36060182/is-it-possible-to-rotate-an-imageview-when-orientation-changes-occur-in-andro
  2.  
  3. на главном активити один имадж вью
  4.  
  5.  
  6. package com.example.delmetmp;
  7.  
  8. import androidx.appcompat.app.AppCompatActivity;
  9.  
  10. import android.content.Context;
  11. import android.hardware.Sensor;
  12. import android.hardware.SensorEvent;
  13. import android.hardware.SensorEventListener;
  14. import android.hardware.SensorManager;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17.  
  18. public class MainActivity extends AppCompatActivity {
  19.  
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. checkOrientation();
  25. }
  26.  
  27.  
  28. public void checkOrientation() {
  29. SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
  30. sensorManager.registerListener(new SensorEventListener() {
  31. int orientation = -1;
  32. @Override
  33. public void onSensorChanged(SensorEvent event) {
  34. if (event.values[1] < 6.5 && event.values[1] > -6.5) {
  35. if (orientation != 1) {
  36. Log.d("Sensor", "Landscape");
  37. findViewById(R.id.imageView).setRotation(90f);
  38. }
  39. orientation = 1;
  40. } else {
  41. if (orientation != 0) {
  42. Log.d("Sensor", "Portrait");
  43. findViewById(R.id.imageView).setRotation(0);
  44. }
  45. orientation = 0;
  46. }
  47. }
  48.  
  49. @Override
  50. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  51. // TODO Auto-generated method stub
  52.  
  53. }
  54. }, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
  55. }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement