在android中为库项目设置不同的主题

arj*_*jun 10 android styles android-manifest android-library android-theme

在包含库项目的android项目中,我需要在主应用程序和库的清单中设置不同的主题.就像我需要在主项目中设置以下主题

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorPrimary">@color/grey</item>
  <item name="colorPrimaryDark">@color/black</item>
  <item name="colorAccent">@color/green</item>
</style>
Run Code Online (Sandbox Code Playgroud)

以及图书馆项目下面的那个

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorPrimary">@color/blue</item>
  <item name="colorPrimaryDark">@color/red</item>
  <item name="colorAccent">@color/white</item>
</style>
Run Code Online (Sandbox Code Playgroud)

主应用程序样式会覆盖库项目样式.当我为样式指定不同的名称时,它会抛出明显的合并冲突错误.

以下是主应用程序的清单

<application
  android:name=".MyApp"
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:supportsRtl="true"
  android:theme="@style/AppTheme">
Run Code Online (Sandbox Code Playgroud)

这个是图书馆的

<application
  android:allowBackup="true"
  android:label="@string/app_name"
  android:supportsRtl="true"
  android:theme="@style/AppTheme"
  >
Run Code Online (Sandbox Code Playgroud)

Ren*_*han 12

构建应用程序后,gradle会将您的清单文件合并为一个,因此设置主题到application库中的标记将被应用程序的属性覆盖.

将您的样式名称更改为其他名称,

<style name="MyLibTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorPrimary">@color/blue</item>
  <item name="colorPrimaryDark">@color/red</item>
  <item name="colorAccent">@color/white</item>
</style>
Run Code Online (Sandbox Code Playgroud)

如果要在库函数中启动某些活动,则在库清单文件中单独将主题设置为活动application.在项目构建后,在库清单上的标记上设置的项目将被替换,因此为各个活动设置主题

   <activity android:name=".MyLibActivity" android:theme="@style/MyLibTheme">
    </activity>
Run Code Online (Sandbox Code Playgroud)

或者您可以在活动代码中使用setTheme.

setTheme(R.style.MyLibTheme);
Run Code Online (Sandbox Code Playgroud)

在构建过程中,如果用户(库用户)使用相同的主题名称,它将替换为主app模块主题,为了保护这种情况,您可以在库的gradle文件中使用gradle选项.

android{
  // replace mylib_ with name related to your library
  resourcePrefix 'mylib_'
}
Run Code Online (Sandbox Code Playgroud)

  • 为个人活动设置主题是可行的,但有没有办法在图书馆中为整个项目设置主题。 (2认同)