Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set different theme for library project in android

In an android project which consists of a library project, I need to have a different theme set in manifest for main app and library. Like I need to set below theme in the main project

<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>

and the one below for library project

<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>

Library project styles are overridden by main app styles. when I give different names for styles it throws manifest merger conflict error.

Below is the manifest of main app

<application
  android:name=".MyApp"
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:supportsRtl="true"
  android:theme="@style/AppTheme">

and this one is for library

<application
  android:allowBackup="true"
  android:label="@string/app_name"
  android:supportsRtl="true"
  android:theme="@style/AppTheme"
  >
like image 958
arjun Avatar asked Mar 16 '17 05:03

arjun


2 Answers

After building your app, gradle will merge your manifest files into one, so setting theme to application tag in library will be overridden by app's attributes.

Change your style name to a different name,

<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>

If you are starting some activity in your library functions, then set the theme to activities individually in library manifest file.Theme set on application tag on your library manifest will be replaced on merge after project build, so set theme for individual activity

   <activity android:name=".MyLibActivity" android:theme="@style/MyLibTheme">
    </activity>

or you can use setTheme in your activity code.

setTheme(R.style.MyLibTheme);

On build process if the user (library user) is using your same theme name it will be replaced with main app module theme, to protect that situation you can use gradle option in your library's gradle file.

android{
  // replace mylib_ with name related to your library
  resourcePrefix 'mylib_'
}
like image 188
Renjith Thankachan Avatar answered Oct 05 '22 19:10

Renjith Thankachan


I think you might want to use tools:replace="android:theme" under application node in the manifest of the main project. You can find the details and more here: https://developer.android.com/studio/build/manifest-merge

like image 28
salbury Avatar answered Oct 05 '22 18:10

salbury