Android 设置横屏竖屏

来源:互联网 发布:朱棣是朱元璋亲生 知乎 编辑:程序博客网 时间:2024/06/07 04:00

1 因为横屏与竖屏需要请求系统设置,因此在AndroidManifest.xml中需要添加权限申请

<uses-permission android:name = "android.permission.CHANGE_CONFIGURATION"/>

2 xml中添加一个按钮,点击按钮若界面为横屏切换为竖屏,若界面为竖屏,切换为横屏

xml代码为

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width = "match_parent"    android:layout_height="match_parent"    android:orientation = "vertical" >    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="切换屏幕 "/>    </RelativeLayout>

3  在Activity中添加按钮的事件响应

btn.setOnClickListener(new OnClickListener() {   public void onClick(View arg0) {// TODO Auto-generated method stubint b = m;Configuration  config = getResources().getConfiguration();//获取当前系统配置信息if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//切换为横屏}if(config.orientation == Configuration.ORIENTATION_PORTRAIT)//如果是竖屏{MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 切换为竖屏}}});

Configuration 类主要用来描述与能让应用程序获取的系统的硬件配置信息,主要包括字体大小,屏幕方向等

setRequestdOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) 为通过程序改变屏幕的方向,主要包括

1  landscape  横屏

2 portrait  竖屏

3 user  用户当前的首选方向

4 behind 继承Activity堆栈中当前Activity下面的那个Activity的方向; 

sensor:由物理感应器决定显示方向,它取决于用户如何持有设备,当 设备 被旋转时方向会随之变化——在横屏与竖屏之间; 

nosensor:忽略物理感应器——即显示方向与物理感应器无关,不管用户如何旋转设备显示方向都不会随着改变("unspecified"设置除外); 





0 0
原创粉丝点击