2011-06-09 44 views

回答

29

你有两个选择:

在你的清单,把:

<activity android:name=".HelloAndroid" 
    android:label="@string/app_name" 
    android:configChanges="orientation"> 

而且,在代码中,覆盖onConfigurationChanged

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    setContentView(R.layout.main);  
    // TODO 
} 

下面是关于它的好tutorial

+0

@ferostar待办事项配置更改报告设备方向更改或ui方向更改?第一个看起来很清楚,因为它使用了传感器管理器。我不确定第二个。 – Mark13426 2016-10-26 19:19:58

+0

从API级别13开始,清单configChanges属性需要为:“orientation | screenSize”。请参阅此答案以获取更多信息:https://stackoverflow.com/questions/5620033/onconfigurationchanged-not-getting-called – user885232 2017-10-20 16:18:18

15

在您的活动中,您可以重写此方法来侦听方向更改并实现自己的代码。

public void onConfigurationChanged (Configuration newConfig) 

Configuration类具有int常量ORIENTATION_LANDSCAPEORIENTATION_PORTRAIT,存在对于可以检查NEWCONFIG这样的:

super.onConfigurationChanged(NEWCONFIG);

int orientation=newConfig.orientation; 

switch(orientation) { 

case Configuration.ORIENTATION_LANDSCAPE: 

//to do something 
break; 

case Configuration.ORIENTATION_PORTRAIT: 

//to do something 
break; 

} 
+3

Huang - 您的建议运行良好,只需进行一次编辑。您需要在方法的开头添加'super.onConfigurationChanged(newConfig);'以避免导致异常。 – 2011-11-21 20:11:50

+0

是的,超级电话是必要的。在eclipse中,这行会自动添加。这就是我省略的原因。 – Huang 2011-11-22 00:01:48

+1

从未呼吁:S。即使我把'android:configChanges =“orientation”'放在清单 – IgniteCoders 2016-11-17 01:57:55

4

由于Android 3.2的,你还需要添加 “屏幕尺寸” 在androidmanifest特定活动

所以XML格式的活动宣言将成为

<activity android:name=".ExampleActivity" 
    android:label="@string/app_name" 
    android:configChanges="orientation|screenSize">