安卓:检测方向更改 [英] Android: Detect Orientation Changed
问题描述
我需要检测的方向变化在我的应用程序,但我不希望我的布局从纵向改为横向。
目前我使用了 OrientationEventListener
然而,检测的方位角度是不够的。欲检测用户从纵向改变为横向或反之亦然,这不只是检测是否取向角为90°或270版
我想要做同样的检测是在Android确实改变活动的orientantion。我试图重写 onConfigurationChanged
并检查是否orientantion是横向/纵向,但是这仍然改变我的活动布局到景观。
有没有一种方法使用onConfigurationChanged但强制布局留在肖像?
有另一种方式来检测orientantion变化,而无需使用 OrientationEventListener
。最后,我可以实现我自己的方向变化的算法,在此任何想法?它有什么东西比更复杂的,如果(90阈值< =取向< = 90 +阈值)
,我想检测用户是否做了完整的运动人像 - >横向或Landscape->人像
I need to detect an orientation change in my application, but I don't want my layout to be changed from portrait to landscape.
Currently I'm using the OrientationEventListener
however detecting the orientation angle is not enough. I want to detect that the user changed from portrait to landscape or viceversa, and that is not just detecting if the orientation angle is 90 or 270.
I want to do the same detection that the Android does to change the activity's orientantion. I tried overriding onConfigurationChanged
and check if orientantion is landscape/portrait, however this still changes my activity layout to landscape.
Is there a way to use onConfigurationChanged but force the layout to stay in portrait?
Is there another way to detect orientantion change without using OrientationEventListener
. Ultimately I can implement my own orientation changed algorithm, any ideas on this? It has to be something more complex than if(90-THRESHOLD <= orientation <= 90+THRESHOLD)
, I want to detect if the user made the complete movement Portrait->Landscape or Landscape->Portrait.
感谢您的帮助,
菲利普
Thanks for the help,
Filipe
推荐答案
好吧,试图使用Android API和不能够做什么,我需要后,我实现了我自己的算法,实际上它并不复杂:
我用了一个OrientationEventListener,如果方向是在4定位点计算(在我的code我只检测 LANDSCAPE_RIGHT
和 PORTRAIT_UP
:
Ok, after trying to use the Android API and not being able to do what I need, I implemented my own algorithm and actually it wasn't that complicated:
I used a OrientationEventListener, and calculated if the orientation is in the 4 orientation points (in my code I only detect LANDSCAPE_RIGHT
and PORTRAIT_UP
:
orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
public void onOrientationChanged(int orientation) {
if(canShow(orientation)){
show();
} else if(canDismiss(orientation)){
dismiss();
}
}
};
@Override
public void onResume(){
super.onResume();
orientationListener.enable();
}
@Override
public void onPause(){
super.onPause();
orientationListener.disable();
}
private boolean isLandscape(int orientation){
return orientation >= (90 - THRESHOLD) && orientation <= (90 + THRESHOLD);
}
private boolean isPortrait(int orientation){
return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD);
}
public boolean canShow(int orientation){
return !visible && isLandscape(orientation);
}
public boolean canDismiss(int orientation){
return visible && !dismissing && isPortrait(orientation);
}
这篇关于安卓:检测方向更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!