在onCreate中使用setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)会永久将您的方向固定为横屏,避免任何方向变化。这就是为什么您的方向被固定且不响应旋转的原因。
以下是另一种可用的方法:
1> 在布局中创建两个视图,即横屏视图和竖屏视图。假设activity_hls_land和activity_hls_port。
2> 在onConfigurationChanged(Configuration newConfig)中使用setContentView(R.layout.activity_hls)代替setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)或setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
以下是示例代码:
public class MainActivity extends Activity {
boolean isLaunched=true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isLaunched){
Toast.makeText(this, "1 st launch " , Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_hls_land);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_hls_port);
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_hls_land );
}
}
}
在清单文件中的活动中添加android:configChanges="orientation"来处理屏幕旋转问题:
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:configChanges="orientation"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
activity_hls_port 的示例布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</LinearLayout>
横屏模式示例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:rotation="90">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</LinearLayout>