您的位置:首页 > 其它

横竖屏切换问题(不使用onConfigurationChanged)

2014-03-05 12:23 405 查看
有这样个需求:要求父Activity横屏(或竖屏),但在弹出的窗口(例如系统配置项)能根据用户的当前手机状态(横屏或者竖屏)进行横竖屏切换

方案1:使用Dialog样式的Activity进行弹窗,然后在子窗口使用onConfigurationChanged进行判断横竖屏。这个方案的问题在于:当你根据用户手机的当前状态(横屏或者竖屏)对弹出的窗口进行横竖屏切换时,你会发现父Activity(已强制横屏或强制竖屏)也会跟着改变!所以此方案不能解决需求。

方案2:使用popupwindows进行弹窗,然后使用传感器(方向传感器 或者 重力传感器)进行判断。该方案的不足之处是,如果你的判断取值不够精确的话,窗口会在横屏和竖屏之间来一直回切换,就是会抖动得很厉害。经过网上查找资料,根本解决方案就是使用android源码内的横竖屏判断方法。整理后的代码如下:

int orientation;
/**
* 横竖屏切换
*/
private SensorEventListener mLsnSensorEvent = new SensorEventListener() {

@Override
public void onSensorChanged(SensorEvent event) {//横屏
if(mFlashOption.isShowing()){
float[] values = event.values;
float X = -values[0];
float Y = -values[1];
float Z = -values[2];
float magnitude = X*X + Y*Y;
if (magnitude * 4 >= Z*Z) {
float OneEightyOverPi = 57.29577957855f;
float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
orientation = 90 - (int)Math.round(angle);
// normalize to 0 - 359 range
while (orientation >= 360) {
orientation -= 360;
}
while (orientation < 0) {
orientation += 360;
}
}
if(dirtChange!=null){
dirtChange.obtainMessage(888, orientation, 0).sendToTarget();
}
}
}

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

}

};
private boolean isHorizontal=true;
private boolean isVertical=false;
private Handler dirtChange=new Handler(){
public void handleMessage(android.os.Message msg) {
if (msg.what==888) {
int orientation = msg.arg1;
if (orientation>45&&orientation<135) {
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
//setRequestedOrientation(8);
}else if (orientation>135&&orientation<225){
//activity.setRequestedOrientation(9);
}else if (orientation>225&&orientation<315){//横屏
changeType=0;
//Log.v("屏幕切换", "横屏");
isVertical=false;
//activity.setRequestedOrientation(0);
}else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){//竖屏
//activity.setRequestedOrientation(1);
changeType=1;
isHorizontal=false;
//Log.v("屏幕切换", "竖屏");
}
if(changeType==0&&!isHorizontal){
mFlashItemHorizontal();
isHorizontal=true;
}
if(changeType==1&&!isVertical){
mFlashItemVertical();
isVertical=true;
}
}
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐