android 学习随笔(屏幕的横屏和竖屏)

本文详细介绍了在Android应用中如何控制屏幕方向,包括禁止横竖屏切换、设置全屏模式以及通过代码实现屏幕方向的动态调整。同时,提供了解决方案避免Activity重启的问题,并展示了获取屏幕宽高及不同屏幕尺寸下的适配方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章出处:http://blog.sina.com.cn/s/blog_8b7a15530101bo0w.html


1、有关android中横屏和竖屏的值: 在某些场合可能需要禁止横屏和竖屏切换,实现这个要求很简单,只要在AndroidManifest.xml里面加入这一行android:screenOrientation="landscape "(landscape 是横向,portrait 是纵向)。不过android中每次屏幕的切换都会重启Activity,所以要在Activity销毁前保存当前活动的状态,在Activity再次创建Create的时候载入配置。在activity加上android:configChanges="keyboardHidden|orientation"属性,就不会重启activity.而是去调用onConfigurationChanged(Configuration newConfig).

 

@Override
 public void onConfigurationChanged(Configuration newConfig) {
 try {
 super.onConfigurationChanged(newConfig);
 if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
 // land
 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
 // port
 }
} catch (Exception ex) {
}

}

2、getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置成全屏模式


setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE););//强制为横屏

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏


requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏


 

设置屏幕显示模式ScreenOrientation.

在activity里设置android:screenOrientation的值。
android:screenOrientation的属性有以下值:


  1. unspecified(默 认值,由系统判断状态自动切换)
  2. landscape,横屏
  3. portrait,竖屏
  4. user(用户当前设置的orientation值)
  5. behind(下一个要显示的Activity的orientation值)
  6. sensor(传 感器的方向)
  7. nosensor(不 使用传感器,这个效果差不多等于unspecified).

获得当前屏幕宽高的方法.

Display display = getWindowManager().getDefaultDisplay(); 
Config.screenWidth = display.getWidth();//宽度
 Config.screenHeight = display.getHeight()//;高度
但是getWidth()和getHeight()这俩个方法在API13之后,官方就废弃了这两个方法。

替代的方法:
DisplayMetrics dm = new
DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); SCREEN_WIDTH = dm.widthPixels; SCREEN_HEIGHT = dm.heightPixels;

解析heightPixels和widthPixels:
public int     heightPixels     The absolute height of the display in pixels.
public int     widthPixels     The absolute width of the display in pixels.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值