0

我正在尝试在eclipse中编写一个Android程序。该程序的想法是,TextView如果设备恰好旋转 180 度(我认为是在 xy 平面上?),则显示“设备已翻转”的消息。我正在使用旋转传感器并尝试在onSensorChanged事件中编写我的代码。目前,此代码应该在检测到任何旋转时更改 TextView,但事实并非如此。

所以我的问题很简单:

  1. 给定任何旋转,我如何让 textview 改变?
  2. 然后如何将其应用于 180 度的旋转?


package com.example.rotation2;

import android.hardware.*;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;


public class MainActivity extends Activity implements SensorEventListener {

TextView message;
private SensorManager mSensorManager;
private Sensor rotation;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);

    TextView message = ((TextView) findViewById(R.id.message_view));


    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    rotation = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
    if (rotation != null){
      // Success! There's a rotation sensor.
        message.setText(R.string.compatible);
      }
    else {
      // Failure! No rotation sensor.
        message.setText(R.string.incompatible);
      }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

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

@Override
public void onSensorChanged(SensorEvent event) {
    message.setText(R.string.rotated);

}


}
4

2 回答 2

0

试试这个:

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
      txtView.setText("Orientation Changed");
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        txtView.setText("Orientation Changed");
    }
}

如果要检测键盘可见性:

if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
  Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
  Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
}
于 2013-08-28T10:30:41.167 回答
0

在 Activity 中覆盖此方法:

 public void onConfigurationChanged(Configuration newConfig) { 
   super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
       Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
       Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
  }

在 Android Manifest 文件中,在活动下提到这一点

android:configChanges="orientation|screenSize".
于 2013-08-28T13:10:58.177 回答