我尝试使用 getResources()。getConfiguration()。orientation 在 Android Fragment 中获取屏幕方向,但它返回相同的结果即使我以纵向和横向模式旋转设备。我还在onConfigurationChanged()中使用了(参见下面的代码),并且作为参数接收的配置报告了corect屏幕方向,但获取屏幕方向的通用方法始终报告活动开始的相同方向模式(横向或纵向)
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
Log.e(TAG, "NEW CONFIG: ORIENTATION_LANDSCAPE");
else
Log.e(TAG, "NEW CONFIG: ORIENTATION_PORTRAIT");
Configuration config = getResources().getConfiguration();
if(config.orientation == Configuration.ORIENTATION_PORTRAIT)
Log.e(TAG, "config: PORTRAIT");
else
Log.e(TAG, "config: LANDSCAPE");
LayoutInflater inflater = LayoutInflater.from(getActivity());
populateViewForOrientation(inflater, (ViewGroup)getView());
}
例如,如果活动在landsape模式下启动,则第一个日志输出将为:
1.a" NEW CONFIG:ORIENTATION_LANDSCAPE"
1.b" config:LANDSCAPE"
我以纵向模式旋转设备后:
2.a" NEW CONFIG:ORIENTATION_PORTRAIT"
2.b" config:LANDSCAPE"
您可以注意到,即使设备具有不同的方向模式,配置也会报告相同的方向模式。
那么这里发生了什么?谢谢! :)
答案 0 :(得分:1)
有时,简单的解决方案不是与系统作斗争,只是接受事实。只需在配置更改时更新配置即可。
试试这个:
private Configuration configuration;
private int getOrientation(){
return getConfiguration().orientation;
}
private Configuration getConfiguration(){
if (configuration == null) {
configuration = getResources().getConfiguration();
}
return configuration;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
configuration = newConfig;
}