【问题标题】:How to detect screen TILT in android?如何在android中检测屏幕倾斜?
【发布时间】:2016-10-18 15:24:54
【问题描述】:

我正在创建一个应用程序,我想在其中检测屏幕倾斜(当我们将手机向右转动一点时)并希望在这种情况下旋转 imageview(到 90 度)。目前我正在使用此代码,但它只是在 oncreate 中旋转图像视图(当应用程序开始运行时)。我想检测屏幕倾斜并想在这种情况下旋转图像视图。如何实现?任何帮助将不胜感激

Sensor accelator;
SensorManager sm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    imageView=(ImageView)findViewById(R.id.iv_demo_img);
    imageView.setBackgroundResource(R.drawable.demoimg);
    relativeLayout=(RelativeLayout)findViewById(R.id.content_main);
    //scaleGestureDetector=new ScaleGestureDetector(this,new ScaleListener());
    setlisteners();
    sm=(SensorManager)getSystemService(SENSOR_SERVICE);
    accelator=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sm.registerListener(this,accelator,SensorManager.AXIS_MINUS_X);
}
@Override
public void onSensorChanged(SensorEvent event) {
    Toast.makeText(this, "On Sensor Changed Called", Toast.LENGTH_SHORT).show();
    imageView.setRotation(90);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

【问题讨论】:

    标签: android rotation


    【解决方案1】:

    使用OrientationEventListener

    private OrientationEventListener createOrientationListener() {
        return new OrientationEventListener(this) {
            public void onOrientationChanged(int orientation) {
                System.out.println("orientation................."+orientation);
            }
        };
    }
    

    onCreate 方法中启动这个监听器。

    OrientationEventListener orientationListener = createOrientationListener();
    orientationListener.enable();
    

    如果您将手机朝正确的方向转动,它会触发 1 到 90 的值。向所有方向转动会给出高达 360 的值。因此您可以根据需要使用此值。

    使用后可以禁用。

    orientationListener.disable();
    

    【讨论】:

      猜你喜欢
      • 2016-01-09
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多