设置 AndroidManifest 的活动 screenRotation 每个风味不同

jes*_*nte 5 android android-manifest build.gradle android-gradle-plugin

有没有办法从 gradle 的 build.config 动态设置 AndroidManifest 中的活动 screenOrientation?

我需要一种允许旋转的风味,以及另一种仅用于肖像的风味。

我已经通读了http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger但他们的例子似乎只适用于普通的字符串标签。

我试过两种方法。

使用 gradle 的 manifestPlaceholders: build.gradle:

productFlavors {
  flavorRotation {
    manifestPlaceholders = [ROTATION_PREF: "unspecified"]
  }
  flavorNoRotation {
    manifestPlaceholders = [ROTATION_PREF: "portrait"]
  }
}
Run Code Online (Sandbox Code Playgroud)

使用 AndroidManifest.xml:

...
  <activity android:name=".ui.ActivityName"
    android:screenOrientation="${ROTATION_PREF}"/>
...
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,没有给出错误,但是当我构建“flavorNoRotation”时旋转没有锁定到纵向


并尝试使用 gradle 的 resValue: build.gradle:

productFlavors {
  flavorRotation {
    resValue "string", "orientation", "unspecified"
  }
  flavorNoRotation {
    resValue "string", "orientation", "portrait"
  }
}
Run Code Online (Sandbox Code Playgroud)

与清单:

...
<activity android:name=".ui.ActivityName"
  android:screenOrientation="@string/orientation"/>
...
Run Code Online (Sandbox Code Playgroud)

这样,它构建得很好,但是当我尝试安装到设备时,它只是失败,Android Studio 给出消息:“安装失败,消息 INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION。如果是,则可以通过卸载现有版本的 apk 来解决此问题存在,然后重新安装。”

单击“确定”只会出现事件日志错误“安装 APK 时出错”。那么,构建类型/口味之间有什么不同的方向吗?

我宁愿避免在 BaseActivity 中以编程方式执行此操作。


编辑:对不起,我尝试了更多,我尝试的第一种方法确实有效。我之前一定是在我自己的设备上安装了错误的构建风格而犯了一个错误。

唯一的问题是 Android Studio 会在“android:screenOrientation="${ROTATION_PREF}”属性上发出警告,说它找不到它,尽管它可以很好地构建和工作。

感谢您的回答尝试。

Dha*_*tap 0

1-Create screen.xml file inside res/values folder and code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="screen_type">phone</string>
</resources>

2-In your activity inside onCreate() after setContentView() check device type

//checking tablets and phones
String screenType = getResources().getString(R.string.screen_type); if (screenType.equals("7-inch-tablet") || screenType.equals("10-inch-tablet")) {

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

} else {

   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} 
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助。