横竖屏切换监听 android

本文介绍了一个Android应用如何通过重写onConfigurationChanged方法来监听屏幕方向的变化,并根据不同方向显示相应的提示信息。

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

  1. @Override  
  2. public void onConfigurationChanged(Configuration newConfig) {  
  3.     super.onConfigurationChanged(newConfig);  
  4.   
  5.     // Checks the orientation of the screen  
  6.     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {  
  7.         Toast.makeText(this"landscape", Toast.LENGTH_SHORT).show();  
  8.     } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){  
  9.         Toast.makeText(this"portrait", Toast.LENGTH_SHORT).show();  
  10.     }  
  11. }  
Android 12系统中,横竖屏切换监听通常通过WindowManager.LayoutParams的flags参数以及DisplayManager类来进行。当设备从横屏切换到竖屏或反之,系统会触发ACTION_CONFIGURATION_CHANGED广播,开发者可以在接收到这个广播后添加相应的BroadcastReceiver来监听屏幕方向的变化。 首先,你需要在AndroidManifest.xml文件中注册BroadcastReceiver: ```xml <receiver android:name=".ScreenOrientationReceiver"> <intent-filter> <action android:name="android.intent.action.CONFIGURATION_CHANGED" /> </intent-filter> </receiver> ``` 然后创建ScreenOrientationReceiver类,并在onReceive()方法中处理屏幕方向变化: ```java public class ScreenOrientationReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_CONFIGURATION_CHANGED)) { Configuration config = context.getResources().getConfiguration(); int orientation = config.orientation; // 根据orientation值判断屏幕方向,比如: switch (orientation) { case Configuration.ORIENTATION_PORTRAIT: // 竖屏 handlePortraitMode(context); break; case Configuration.ORIENTATION_LANDSCAPE: // 横屏 handleLandscapeMode(context); break; // 其他配置变化... } } } private void handlePortraitMode(Context context) { // 处理竖屏模式下的逻辑 } private void handleLandscapeMode(Context context) { // 处理横屏模式下的逻辑 } } ``` 在handlePortraitMode()和handleLandscapeMode()方法中,你可以添加你的逻辑,比如更新UI布局、改变视图的方向等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值