Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View with Layer-List background drawable renders black screen

I'm trying to build a custom android view and apply a background drawable that is a layer-list.

The layer-list has two items:

  1. A background color (white)
  2. A simple shape drawable that is a stroked rectangle with rounded-corners

here's the drawable xml:

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white"/>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <corners android:radius="1dp" />
            <stroke
                android:width="2dp"
                android:color="@color/background_green" />
        </shape>
    </item>
</layer-list>

The custom view is a class derving from Android.view.View that currently has NO functionality except the required measuring overloads.

I'm applying the background in the view definition in an activity layout:

<view
    android:layout_width="match_parent"
    android:layout_height="300dp"
    class="com.example.widget.TestView"
    android:id="@+id/view2"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/rect_sig_cap"
    android:layout_margin="20dp" />

What I expect to see is a view with a white background and a green border. What I actually see when I deploy the project is a view with a black background and a green border.

Interestingly it appears correctly in the designer preview in Android Studio. It's only when I deploy it to a device that it renders black.

Am I missing something obvious here?

like image 517
pdriegen Avatar asked Nov 01 '13 20:11

pdriegen


1 Answers

For those interested, I found the solution.

I had defined the shape drawable as including only a stroke definition. Without any other inputs, this causes the fill color to be inferred as black.

In the end, a Layer-List drawable is not required at all. Instead, add a solid fill definition to the shape layer with color Transparent and it works just fine.

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="@dimen/corner_radius" />
    <stroke android:width="1dp"
        android:color="@color/background_green" />
    <solid android:color="@android:color/transparent" />
</shape>
like image 75
pdriegen Avatar answered Oct 11 '22 06:10

pdriegen