LoginSignup
1
1

Android 9以下ではandroid:backgroundで@colorを指定できない件

Posted at

タイトルの通り、Viewの背景にべた塗りの色を指定したくて、以下のように指定しました

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/primary_50"
    android:text="Hello World!"
    />

結果、Android9以下で

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MainActivity}: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class TextView
...
Caused by: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class TextView
Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class TextView
Caused by: android.content.res.Resources$NotFoundException: Drawable com.example:color/primary_50 with resource ID #0x7f0502f0
Caused by: android.content.res.Resources$NotFoundException: File res/color/primary_50.xml from drawable resource ID #0x7f0502f0

って感じでクラッシュしてしまいました。Android 10以上では問題ありません。

原因

実は、このcolor、以下のようにselectorで定義していたのでした。
※colors.xmlで定義した色であれば問題ありません。

primary_50.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:alpha="0.5" android:color="?attr/colorPrimary" />
</selector>

これ自体はテーマカラーにアルファ値を設定するテクニックであり、間違っているわけでも、Android 9以下でサポートされていないというわけでもありません。
ただ、android:backgroundでxmlリソースを指定した場合、Android 9以下ではdrawableを期待してパースされるので、クラッシュしてしまったようでした。

対策

selectorを使ったcolorの定義が悪いわけでも無く、Android 9以下でも問題無く使えます。ただ、android:backgroundで指定できないというだけです。

なので、以下のようにこの色をべた塗りするdrawableを定義し

bg_primary.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/primary_50" />
</shape>

以下のようにdrawableを指定すると問題無く動作します。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_primary"
    android:text="Hello World!"
    />

コンパイル時点で問題は検出されないですし、上位バージョンであれば問題無く動作する記述というのは、見逃してしまいがちです。気をつけましょう。

以上です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1