【问题标题】:Activity turns to landscape after opening the camera打开相机后Activity变成横向
【发布时间】:2018-06-13 12:19:23
【问题描述】:

当我打开相机时,我的 Activity 会转一秒钟变成横向,然后再转回纵向,之后我的 ListView 中的所有数据都消失了。你知道如何解决这个问题吗?

我尝试使用 SCREEN_ORIENTATION_PORTRAIT 但它对我不起作用。

这是我的代码。

private void onClick() {

        scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);

                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setPrompt("Scan Code");
                integrator.setBeepEnabled(false);
                integrator.setCameraId(0);
                integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);


        if (result != null) {

            scandata = result.getContents();
            scanFormat = result.getFormatName();

            if (scandata != null) {
                dta.add("Data: " + scandata + "     Format: " + scanFormat);

            }
        }



    }

【问题讨论】:

  • AndroidManifest.xml 文件android:screenOrientation="portrait" 中将此标签添加到您的活动(您希望它始终处于纵向模式的活动)中
  • 它不起作用。它只转了一秒钟就变成了横向,然后又变成了纵向
  • 在你的活动的 AndroidManifest 中添加这个 -android:configChanges="orientation|screenSize"
  • 旋转后ListView 数据为空的原因很可能是数据和视图紧密耦合。考虑使用架构来解耦数据和视图(例如 MVP、MVVM 等),或在配置更改之间传递数据(例如使用onSaveInstanceState

标签: android android-layout listview android-camera-intent


【解决方案1】:

您的设备表现不佳,但您不应绝望。如果您添加一个“代理”活动,它将隐藏列表并负责启动相机意图并处理结果,您的主要活动将受到保护,不会发生不必要的旋转。

另一方面,空列表视图可能仍会再次出现,如果不是在您的设备上,然后在您客户的设备上,尤其是在 RAM 较小或相机应用程序不佳的设备上。

您应该在必要时保存和恢复您的活动状态,如本经典 answer 中所述。

【讨论】:

    【解决方案2】:

    在 manifest.xml 中添加一个标签 android:screenOrientation="portrait",用于在肖像模式下您想要的活动

    所以你的代码看起来像:

     <activity
                android:name=".MainActivity"
                android:screenOrientation="portrait" />
    

    【讨论】:

    • 它不起作用。它只转了一秒钟就变成了横向,然后又变成了纵向
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多