我已经创建了方向检测功能,但它无法正常工作,我需要在方向向左或向右改变时收到通知。我使用OrientationEventListener专门做了这个,因为我不希望因为原因而使用OnConfigurationChanged。
int orentation; // 0 - Portariat; 1 - Right; 2 - Left
int new_orentation;
orentation = 0;
new_orentation = 0;
myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){
@Override
public void onOrientationChanged(int arg0) {
orent.setText("Orientation: " + String.valueOf(arg0));
switch (orentation) {
case 0:
if (arg0 > 60)
new_orentation = 1;
else if (arg0 < 300)
new_orentation = 2;
break;
case 1:
if (arg0 < 30)
new_orentation = 0;
else if (arg0 < 300)
new_orentation = 2;
break;
case 2:
if (arg0 > 330)
new_orentation = 0;
else if (arg0 > 300)
new_orentation = 1;
break;
default:
break;
}
if (orentation!=new_orentation)
{
switch (new_orentation) {
case 0:
Toast.makeText(getApplicationContext(), "Normal", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "Right", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
orentation = new_orentation;
}
}};
答案 0 :(得分:1)
似乎param没有声明差异而是绝对位置。它似乎应该是你正在使用的开关/案例是不合适的。也许更喜欢的东西(相应地调整你想要如何准确定义每个案例):
if(arg0 <= 90){
new_orentation = 1;
}
else if(arg0 <=180){
//this is reversePortrait
new_orentation = 0;
}
else if(arg0 <= 270){
new_orentation = 2;
}
else{
new_orentation = 0;
}