Home > Software design >  use conditional statement with theme Android DataBinding
use conditional statement with theme Android DataBinding

Time:08-25

I wan to set the theme of root view based on a condition, but faced error.

what I used:

  <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/dimen_16dp"
        android:theme="@{ isDarker ? @style/DarkerCardThem : @style/LighterCardThem}">

error:

Could not find identifier 'DarkerCardThem' Check that the identifier is spelled correctly, and that no <import> or <variable> tags are missing

the style:

    <style name="DarkerCardThem">
        <item name="android:textColor">@color/darker_card_color</item>
    </style>

CodePudding user response:

You can use @BindingAdapter for this purpose.

@BindingAdapter("setThemeC")
fun ConstraintLayout.setThemeC(isDarker : Boolean) {
    /*.....*/
}

After that in your code:

  <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/dimen_16dp"
        setThemeC="@{isDarker}">

Use: setThemeC(Boolean) to enable the functionality.

Could not find identifier 'DarkerCardThem' Check that the identifier is spelled correctly, and that no <import> or <variable> tags are missing

It's clear that, you can use those tags in the <layout></layout> section not <style>

CodePudding user response:

hello mahmoud i think it's impasbole to do that but if you want to change theme you can do it in your code before setContentView

    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
  • Related