如何在Android中检测布局的方向变化?

如何解决如何在Android中检测布局的方向变化?

| 我刚刚实现了方向更改功能-例如当布局从纵向更改为横向时(反之亦然)。如何检测方向更改事件何时结束。
OrientationEventListener
不起作用。如何获得有关布局方向更改事件的通知?

解决方法

使用Activity的onConfigurationChanged方法。 请参见以下代码:
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this,\"landscape\",Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this,\"portrait\",Toast.LENGTH_SHORT).show();
    }
}
您还必须在清单文件中编辑适当的元素,以包含android:configChanges 请看下面的代码:
<activity android:name=\".MyActivity\"
          android:configChanges=\"orientation|keyboardHidden\"
          android:label=\"@string/app_name\">
注意:在Android 3.2(API级别13)或更高版本中,当设备在纵向和横向之间切换时,“屏幕尺寸”也会更改。因此,如果要防止在开发API级别13或更高版本时由于方向改变而导致运行时重启,则必须声明API级别13或更高版本的android:configChanges = \“ orientation | screenSize \”。 希望这能够帮到你... :),要将布局加载到layout-land文件夹中,意味着您有两个单独的布局,然后必须用
onConfigurationChanged
方法制作
setContentView
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.yourxmlinlayout-land);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.yourxmlinlayoutfolder);
    }
}
如果只有一个布局,则无需在此方法中设置setContentView。只是
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}
,只是想向您展示一种在onConfigurationChanged之后保存所有Bundle的方法: 在课程结束后创建新的捆绑包:
public class MainActivity extends Activity {
    Bundle newBundy = new Bundle();
接下来,在“ protected void onCreate”之后添加以下内容:
@Override
public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            onSaveInstanceState(newBundy);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            onSaveInstanceState(newBundy);
        }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBundle(\"newBundy\",newBundy);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    savedInstanceState.getBundle(\"newBundy\");
}
如果添加此选项,则所有创建的类都将保存到MainActivity中。 但是最好的方法是在AndroidManifest中添加以下代码:
<activity name= \".MainActivity\" android:configChanges=\"orientation|screenSize\"/>
,使用这种方法
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        Toast.makeText(getActivity(),\"PORTRAIT\",Toast.LENGTH_LONG).show();
       //add your code what you want to do when screen on PORTRAIT MODE
    }
    else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        Toast.makeText(getActivity(),\"LANDSCAPE\",Toast.LENGTH_LONG).show();
        //add your code what you want to do when screen on LANDSCAPE MODE
   }
}
并且不要忘记在Androidmainfest.xml中添加它
android:configChanges=\"orientation|screenSize\"
像这样
<activity android:name=\".MainActivity\"
          android:theme=\"@style/Theme.AppCompat.NoActionBar\"
          android:configChanges=\"orientation|screenSize\">

    </activity>
,覆盖活动的onConfigurationChanged方法,如上所述,事实上,我只想提出另一种与您有关的替代方法:
android:configChanges=\"orientation|keyboardHidden\" 
表示我们显式声明要注入的布局。 万一我们希望保留自动注入功能,这要归功于layout-land和layout文件夹。您所要做的就是将其添加到onCreate中:
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();

    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        getSupportActionBar().show();
    }
在这里,我们根据手机的方向显示或不显示操作栏,创建一个“ 0”类的实例并启用它。
OrientationEventListener mOrientationEventListener = new OrientationEventListener(YourActivity.this) {
    @Override
    public void onOrientationChanged(int orientation) {
        Log.d(TAG,\"orientation = \" + orientation);
    }
};

if (mOrientationEventListener.canDetectOrientation())
    mOrientationEventListener.enable();
,如果接受的答案对您不起作用,请确保您未在​​清单文件中定义:
android:screenOrientation=\"portrait\"
这是我的情况。,如果这对某些较新的开发人员有用,因为上面未指定。只是非常明确: 如果使用onConfigurationChanged,则需要两件事: 活动类中的
onConfigurationChanged
方法 在清单中指定将由
onConfigurationChanged
方法处理的配置更改 上述答案中的清单清单无疑无疑对清单所属的特定应用程序是正确的,但这并不是您在清单中添加触发活动类中的onConfigurationChanged方法的确切要求。也就是说,以下清单条目可能不适用于您的应用。
<activity name= \".MainActivity\" android:configChanges=\"orientation|screenSize\"/>
在上述清单条目中,针对
android:configChanges=\"\"
的各种Android操作可以触发您的Activity生命周期中的onCreate。 这非常重要-清单中未指定的那些触发您的onCreate,清单中指定的那些触发您的Activity类中的
onConfigurationChanged
方法。 因此,您需要确定需要处理的配置更改。对于像我这样的Android百科全书挑战者,我使用了Android Studio中的快速提示弹出窗口,并添加了几乎所有可能的配置选项。列出所有这些基本上表示我将处理所有事情,并且由于配置而永远不会调用onCreate。
<activity name= \".MainActivity\" android:configChanges=\"screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize\"/>
现在显然我不想处理所有事情,因此我开始一次消除了上述选项。每次删除后重新构建和测试我的应用。 另一个要点:如果仅自动处理一个触发您的onCreate的配置选项(上面的清单中没有列出该选项),那么它将显示
onConfigurationChanged
不起作用。您必须将所有相关的内容放入清单中。 我得到了3个最初触发onCreate的结果,然后我在S10 +上进行了测试,但仍然可以使用onCreate,因此我不得不再次进行消除练习,我还需要
|screenSize
。因此,请在多种平台上进行测试。
<activity name= \".MainActivity\" android:configChanges=\"screenLayout|uiMode|orientation|screenSize\"/>
因此,我的建议是,尽管我确定有人可以在此戳破漏洞: 在活动类中添加带有TOAST或LOG的
onConfigurationChanged
方法,以便查看其工作时间。 将所有可能的配置选项添加到清单中。 通过测试您的应用,确认您的
onConfigurationChanged
方法有效。 一次从清单文件中删除每个配置选项,然后逐个测试您的应用程序。 在尽可能多的各种设备上进行测试。 不要将上面的代码段复制/粘贴到清单文件中。 Android更新会更改列表,因此请使用弹出的Android Studio提示来确保全部获取。 我希望这可以节省一些时间。 我的
onConfigurationChanged
方法仅用于以下信息。在新方向可用之后但在重新创建UI之前,将在生命周期中调用“ 4”。因此,我第一个检查方向的
if
可以正常工作,然后第二个嵌套的
if
可以查看UI ImageView的可见性也可以正常工作。
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res