Search code examples
androidandroid-themeandroid-styles

Is there a way to change visibility of an item when switching app theme from styles.xml?


I'm trying to achieve an effect where this starry background animation is visible/gone depending on the selected app theme.

<com.starry.animation
        android:id="@+id/stars"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:starsView_bigStarThreshold="10dp"
        app:starsView_meteoritesColors="@array/meteorites_colors"
        app:starsView_meteoritesEnabled="true"
        app:starsView_meteoritesInterval="2000"
        app:starsView_maxStarSize="3dp"
        app:starsView_minStarSize="1dp"
        android:visibility="?visibilityMode"
        android:background="@android:color/transparent"
        app:starsView_starColors="@array/star_colors_small"
        app:starsView_starCount="100" />

I've declared visibilityMode in styles.xml as string attribute

<attr name="visibilityMode" format="string" />

and in my custom theme as :

<item name="visibilityMode">GONE</item>

This results in an error inflating the stars view. Is there some other implementation I can achieve a similar result?


Solution

  • Actually visibility is not a string but an integer.
    0 is used for visible initial state.
    2 is used for gone initial state
    (don't be confused with View.Gone and View.Visible).

    So in your case the custom attribute may look like:

    <attr name="visibilityMode" format="integer">
      <!-- Visible on screen; the default value. -->
        <enum name="visible" value="0" />
        <!-- Completely hidden, as if the view had not been added. -->
        <enum name="gone" value="2" />
    </atrr>
    

    Than it can be used in theme: <item name="visibilityMode">gone</item>

    and in your layout item: android:visibility="?visibilityMode"

    Please check out this answer