Dynamic theming is a powerful technique for Android apps that need flexible branding. In scenarios like white-label products, enterprise clients, or apps that fetch custom settings from a server, being able to update colors at runtime can save you from maintaining multiple static themes or shipping new builds. In this article, we will explore two practical ways to apply server-defined color schemes in XML-based Android UIs.Dynamic theming is a powerful technique for Android apps that need flexible branding. In scenarios like white-label products, enterprise clients, or apps that fetch custom settings from a server, being able to update colors at runtime can save you from maintaining multiple static themes or shipping new builds. In this article, we will explore two practical ways to apply server-defined color schemes in XML-based Android UIs.

Simple Dynamic Color Schemes in Android Applications

2025/09/02 15:06

Dynamic theming is a powerful technique for Android apps that need flexible branding. In scenarios like white-label products, enterprise clients, or apps that fetch custom settings from a server, being able to update colors at runtime can save you from maintaining multiple static themes or shipping new builds.

In this article, we will explore two practical ways to apply server-defined color schemes in XML-based Android UIs:

  • Manual View Theming
  • Using LayoutInflater.Factory2 We will compare the two approaches in terms of scalability, maintainability, and complexity, and also look briefly at how Jetpack Compose makes dynamic theming first-class.

What Are Dynamic Color Schemes?

A dynamic color scheme lets your app load and apply a palette at runtime, based on user preferences, company branding, or remote configuration. Instead of hardcoding styles or toggling between predefined themes, the app adapts its appearance dynamically, keeping the UI consistent with the source of truth on the server.

Example server response:

{   "primary": "#006EAD",   "secondary": "#00C853",   "background": "#FFFFFF",   "surface": "#F5F5F5",   "onPrimary": "#FFFFFF" } 

(A real-world payload would likely include more fields.)

Setup

We’ll define a simple model to represent our theme colors (omitting DTOs and converters for brevity):

data class ThemeColors(     val primary: Int,     val secondary: Int,     val background: Int,     val surface: Int,     val onPrimary: Int ) 

Approach 1: Manual View Theming

How It Works

After inflating a layout, you manually apply colors to each view using findViewById, setBackgroundColor, setTextColor, etc.

Example:

class MainActivity : AppCompatActivity() {      private val themeColors = ThemeColorsRepository.get( /* from server */ )      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          val root = findViewById<ViewGroup>(R.id.rootLayout)         val toolbar = findViewById<Toolbar>(R.id.toolbar)         val titleText = findViewById<TextView>(R.id.titleText)          toolbar.setBackgroundColor(themeColors.primary)         toolbar.setTitleTextColor(themeColors.onPrimary)         root.setBackgroundColor(themeColors.background)         titleText.setTextColor(themeColors.primary)     } } 

✅ Pros

  • Beginner-friendly and easy to debug.
  • Great for prototypes or theming a few views.

❌ Cons

  • Tedious in multi-screen apps.
  • Easy to miss views and lose consistency.
  • Doesn’t scale well.

Approach 2: Using LayoutInflater.Factory2

What Is It?

LayoutInflater.Factory2 is a lesser-known but powerful Android API. It lets you intercept view inflation globally and apply logic (like theming) as views are created.

How It Works

Instead of styling views manually, you “wrap” the inflation process and automatically apply colors to views as they’re inflated from XML.

Example

class ThemingFactory(     private val baseFactory: LayoutInflater.Factory2?,     private val themeColors: ThemeColors ) : LayoutInflater.Factory2 {      override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {         val view = baseFactory?.onCreateView(parent, name, context, attrs)             ?: LayoutInflater.from(context).createView(parent, name, null, attrs)          applyDynamicTheme(view)         return view      }      override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {         return onCreateView(null, name, context, attrs)     }      private fun applyDynamicTheme(view: View?) {         when (view) {             is TextView -> view.setTextColor(themeColors.primary)             is Button -> {                 view.setBackgroundColor(themeColors.primary)                 view.setTextColor(themeColors.onPrimary)             }             is Toolbar -> {                 view.setBackgroundColor(themeColors.primary)                 view.setTitleTextColor(themeColors.onPrimary)             }         }     } } 

Installation

This must be set before setContentView:

override fun onCreate(savedInstanceState: Bundle?) {     val themeColors = ThemeColors(/* from server */)      val inflater = LayoutInflater.from(this)     val baseFactory = inflater.factory2     LayoutInflaterCompat.setFactory2(inflater, ThemingFactory(baseFactory, themeColors))      super.onCreate(savedInstanceState)     setContentView(R.layout.activity_main) } 

⚠️ Gotcha: With AppCompatActivity, the inflater is overridden internally. If you don’t delegate back to the default AppCompat factory, you’ll lose default styling. A working sample is available here:

  • HomeActivity.kt
  • ThemingFactory.kt

Manual vs Factory2: Feature Comparison

| Feature | Manual View Theming | LayoutInflater.Factory2 Theming | |----|----|----| | Ease of implementation | ✅ Beginner-friendly | ⚠️ Intermediate | | Control per view | ✅ Total | ⚠️ Needs conditionals per view type | | Scalability | ❌ Poor (per view) | ✅ Excellent (global, centralized) | | Boilerplate | ❌ High | ✅ Low | | Reusability | ❌ Limited | ✅ Easy to reuse across screens | | Custom view theming | ❌ Manual only | ✅ Interceptable during inflation | | Dynamic theme switching | ⚠️ Manual re-theming required | ⚠️ Needs re-inflation or restart |

In practice: I applied theming to a large app with dozens of screens in four weeks using LayoutInflater.Factory2. A manual approach would have taken far longer.

Bonus Section: Compose

Jetpack Compose makes it natural to create and apply a custom MaterialTheme dynamically, so you can swap colors at runtime (for example, after fetching them from your server).

Example of implementation:

  1. Define a ThemeColors model (just like in the XML-based version).
  2. Expose it from a ViewModel using StateFlow or LiveData.
  3. Wrap your UI with a MaterialTheme whose colorScheme is derived from ThemeColors.
  4. All Composables that use MaterialTheme.colorScheme will automatically recompose when colors change.

| XML + Factory2 | Jetpack Compose | |----|----| | Manual theming of views (per type) | Global theming via MaterialTheme | | Requires inflating and intercepting views | Native support with recomposition | | Boilerplate-heavy | Minimal, declarative | | Great for legacy codebases | Best for Compose-first apps |

In short, Compose makes dynamic theming a first-class feature, while XML requires custom plumbing (via LayoutInflater.Factory2 or manual updates).

Sample project: Dynamic Theme in Compose

Conclusion

All of the mentioned approaches unlock server-driven dynamic theming, but each fits different needs:

  • Manual theming: Best for small apps, quick prototypes, or theming just a few views.
  • LayoutInflater.Factory2: The way to go for scalable, brand-flexible apps (white-label, multi-client).
  • Jetpack Compose: Dynamic theming is built-in and declarative, ideal for new projects. If you’re working on a legacy XML app, Factory2 will save you huge amounts of time. For new apps, Compose + MaterialTheme is the clear winner.

Further Reading

  • Android Docs: LayoutInflater.Factory2
  • Sample project

\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Trading Moment: Markets Enter a Key Week Ending the Year, Bitcoin Holds Key Level at $86,000

Trading Moment: Markets Enter a Key Week Ending the Year, Bitcoin Holds Key Level at $86,000

Daily market data review and trend analysis, produced by PANews. 1. Market Observation Markets are holding their breath for this week's Federal Reserve meeting, with a 25-basis-point rate cut widely expected. However, contrary to conventional wisdom, since the rate-cutting cycle began in September, the yield on long-term US Treasury bonds, the anchor for global asset pricing, has risen instead of falling, triggering intense debate about the future economic path. Optimists see this as a signal of a "soft landing," while pessimists worry it's a vote of no confidence from the "bond vigilantes" regarding the high national debt and inflation risks in the US. Against this backdrop, Wall Street veteran strategists like Mark Cabana of Bank of America predict that, in addition to rate cuts, the Fed may announce a major balance sheet expansion plan of up to $45 billion per month to address potential liquidity shortages. Meanwhile, China will also usher in a super week of policy announcements, with important meetings and the release of key economic data such as inflation and social financing providing new guidance for the market. Furthermore, competition in the field of artificial intelligence is becoming increasingly fierce, with OpenAI planning to release GPT-5.2 ahead of schedule to address this competition. The financial reports of Broadcom, a chip designer and Oracle, both core players in the AI industry chain, as well as the visit of Microsoft's CEO to India, will all serve as key indicators for assessing the investment climate in AI infrastructure and the future direction of the industry. In the Bitcoin market, short-term sentiment is cautious, but long-term indicators remain resilient. Analyst Murphy, based on the MVRV indicator, predicts that Bitcoin's price may reach $85,000 to $94,000 by December 31st, and then touch the $71,000 to $104,000 range in early 2026, considering $104,000 as a key bull-bear dividing line. Several analysts consider the $86,000 to $88,000 area as key support. For example, Daan Crypto Trades points out that a break below this key Fibonacci level could lead to a price pullback to a low of $76,000, while Michaël van de Poppe believes that holding $86,000 is a prerequisite for his bullish scenario (i.e., a price break above $92,000 and head towards $100,000). On-chain data presents a mixed picture: on the one hand, Glassnode points out that ETF demand continues to weaken, and market risk appetite is declining; on the other hand, analyst @TXMCtrades emphasizes the continued rise in the "activity" indicator, and CryptoQuant data also shows that selling pressure from long-term holders has been "completely reset," which may indicate potential spot demand and the formation of a market bottom. Bloomberg ETF expert Eric Balchunas, however, offers a more macro-level reassurance to the market, believing that Bitcoin's correction this year is merely a normal cooling down of last year's extreme 122% surge. Its resilience in reaching new highs after multiple significant pullbacks makes it no longer suitable for comparison to the "tulip bubble." Regarding Ethereum, short-term market sentiment leans towards pessimism, but long-term technical patterns are showing optimistic signals. According to Nansen data, "smart money" traders are still adding to their short positions in Ethereum on the derivatives platform Hyperliquid, with net short positions accumulating to over $21 million. However, analyst Sykodelic sees a positive side in the technical charts, pointing out that Ethereum's 5-day MACD and RSI indicators, after a thorough reset, are exhibiting patterns that have historically led to significant rallies, suggesting that a market bottom is forming. In the altcoin market, the AI project Bittensor (TAO) became the focus of attention. The project will undergo its first halving on December 14th, reducing the daily token issuance by half. Grayscale analyst Will Ogden Moore commented positively, believing it marks a significant milestone in the network's maturation. He pointed out that its strong adoption momentum, rising institutional interest, and the success of the dTAO mechanism could all be catalysts for price increases. TAO rose nearly 10% intraday. The weekend saw numerous market developments, with several events and figures attracting widespread attention. Terraform Labs co-founder Do Kwon's legal case saw new developments. US prosecutors recommended a 12-year prison sentence for his "massive" fraudulent activities, and US District Judge Paul Engelmayer will deliver sentencing on December 11th. This news initially caused USTC and LUNA tokens to surge by over 100% over the weekend before falling sharply, down nearly 20% in the past 24 hours. Additionally, Binance founder CZ's joke about executive He Yi's misspelling of "DOYR" in a tweet unexpectedly spawned a meme coin with the same name. Meanwhile, Binance responded directly to community concerns, stating that it is conducting an internal review of potential corruption related to token listings. Another noteworthy piece of news comes from the intersection of the tech and cryptocurrency worlds: Moore Threads, the "first domestically produced GPU stock," saw its share price surge after listing on the STAR Market. The controversial past of its co-founder, Li Feng, has also resurfaced, including his involvement in the "Mallego Coin" project with Li Xiaolai and others, and a long-standing debt dispute with OKX founder Star involving 1,500 bitcoins (currently worth approximately $135 million). In response, Star recently stated on social media that the debt issue has been handed over to legal action and that the focus should be on the future. 2. Key Data (as of 13:00 HKT, December 8) (Data source: CoinAnk, Upbit, Coingecko, SoSoValue, CoinMarketCap) Bitcoin: $91,596 (down 2.11% year-to-date), daily spot trading volume $40.49 billion. Ethereum: $3,134 (down 6.17% year-to-date), daily spot trading volume $25.27 billion. Fear of Greed Index: 20 (Extreme Fear) Average GAS: BTC: 1.2 sat/vB, ETH: 0.04 Gwei Market share: BTC 58.7%, ETH 12.2% Upbit 24-hour trading volume rankings: XRP, ETH, BTC, MOODENG, SOL 24-hour BTC long/short ratio: 50.54% / 49.46% Sector Performance: Meme and DeFi sectors saw a slight pullback, while SocialFi and AI rose by over 2%. 24-hour liquidation data: A total of 112,699 people worldwide were liquidated, with a total liquidation amount of $416 million. This included $105 million in BTC liquidations, $169 million in ETH liquidations, and $21.92 million in SOL liquidations. 3. ETF Flows (as of December 5) Bitcoin ETFs saw a net outflow of $87.77 million last week, with ARKB experiencing the largest net outflow at $77.86 million. Ethereum ETFs saw net outflows of $65.59 million last week, with BlackRock's ETHA experiencing the largest net outflow at $55.87 million. Solana ETF: Net inflow of $20.3 million last week XRP ETF: Net inflows of $231 million last week, marking the fourth consecutive week of net inflows. 4. Today's Outlook HumidiFi: New token public sale will begin on December 8th at 23:00. The Stable mainnet will launch on December 8th at 21:00. The company formed by the merger of Twenty One Capital and CEP is expected to list on the NYSE on December 9. BounceBit (BB) will unlock approximately 29.93 million tokens at 8:00 AM Beijing time on December 9th, representing 3.42% of the circulating supply, worth approximately $2.7 million. The top 100 cryptocurrencies by market capitalization with the largest gains today are: Ultima up 7%, SPX6900 up 5.8%, Canton Network up 5.5%, Ethena up 5.1%, and Zcash up 4.5%. 5. Hot News Data: APT, LINEA, CHEEL and other tokens will see large-scale unlocking, with APT unlocking value estimated at approximately $19.3 million. This Week's Preview | The Federal Reserve FOMC announces its interest rate decision; the Stable blockchain mainnet will officially launch on December 8th. The largest short position in BTC on Hyperliquid currently has a floating profit of approximately $17 million, having reduced its position by about 20 BTC in 26 minutes. The BEAT team's linked wallet sent $1.2 million worth of tokens to a CEX, seemingly indicating a planned sell-off for profit. Twenty One Capital transferred 43,122 BTC to a new wallet. The U.S. SEC's Cryptocurrency Working Group will hold a roundtable meeting on financial regulation and privacy on December 15. Bittensor will undergo its first halving on December 14th, at which time the daily supply of TAO will decrease to 3600 tokens. ZKsync plans to abandon its early network, ZKsync Lite, in 2026. The long positions held by the "whale that opened short positions after the 1011 flash crash" have reached $164 million, and are currently showing a floating loss of $950,000. A wallet suspected to be Windemute has accumulated approximately $5.2 million worth of SYRUP tokens over the past two weeks. South Korea is considering legislation requiring virtual asset operators to bear "no-fault liability" for hacker attacks, with fines potentially increased to 3% of sales revenue. The average cash cost for public miners mining Bitcoin has reached $74,600, with a total cost of $137,800. Caixin: Last year, 3,032 people were prosecuted for money laundering related to cryptocurrencies; establishing a firewall against virtual currencies is necessary to protect normal economic and trade activities. Farcaster announces strategic shift: from a social-first approach to wallet-driven growth.
Share
PANews2025/12/08 14:48
Robinhood Sets Indonesia Footprint Through Crypto Trader, Brokerage Firms Acquisition

Robinhood Sets Indonesia Footprint Through Crypto Trader, Brokerage Firms Acquisition

Robinhood Markets has announced two key acquisitions, marking its official entry into the Indonesian market. The American financial services firm has
Share
CryptoNews2025/12/08 14:45