3

I'm following google's excellent blog post to make a dark theme for my app, but I don't see any reference on how I get the elevation effects on my views(buttons, app bar, etc) to work. For example when I set my app theme to <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> and make a button or a card like so:

        <Button
        android:id="@+id/keypadOne"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/surface"
        android:elevation="01dp"
        android:text="@string/one"
        android:textColor="@color/onSurface"
        android:textSize="36sp" />

I would expect to see the effect that makes the object appear lighter due to the semi-transparent white overlay used in dark themes to imply elevation or being closer to a light source than the background. Instead, my buttons,action bar, etc, are the same color as the background and therefore invisible.

My questions are:

  1. Do I have to implement this elevation functionality manually or is that provided by the Material library?
  2. If I get this working automatically for Android 10+ will I have to implement a manual solution for backwards compatibility on versions 9 and earlier?
Cody
  • 1,801
  • 3
  • 28
  • 53

2 Answers2

4

I've found the solution. In order to achieve the overlay tinting effect on elevation for CardViews you have to use the Material lib's special object that contains this functionality: MaterialCardView. Once you use this CardView, set it's app:cardElevation attribute to change the white overlay mentioned in the google blog post on Dark Mode I linked above.

For example, my CardView looks like this now:

    <com.google.android.material.card.MaterialCardView 
android:id="@+id/testCard" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:elevation="18dp" app:cardCornerRadius="4dp" />

Note that this special elevation attribute is only available for MaterialCardViews, despite other views like Toolbars having a Material version.

Ananiya Jemberu
  • 1,366
  • 1
  • 9
  • 14
Cody
  • 1,801
  • 3
  • 28
  • 53
2

First make sure your using material components library theme and DayNight variant like this

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">

this should automatically change surface color for AppBarLayout, Toolbar and MaterialCardView but if you want to set this auto surface color change based on elevation for others view set your

android:background="?attr/colorSurface" or in case of MaterialCardView use this app:cardBackgroundColor="?attr/colorSurface" and apply elevation with

android:elevation="4dp" or in some cases without android namespace elevation="4dp" or in case of MaterialCardView use this app:cardElevation="4dp"

Burhan Khanzada
  • 945
  • 9
  • 27