【Android Studio】contentDescription属性のWarning解消方法

この記事では ImageView や ImageButton に表示される contentDescription の Warning 解消法を紹介しています。
ImageView や ImageButton の色が変わっている部分にカーソルを合わせると Missing contentDescription attribute on image と表示されます。

これは contentDescription 属性がありませんという Warning です。
contentDescription 属性は「ImageView に指定している画像が何を意味するのか、どんな画像なのか」を示すものです。
TalkBack など目が不自由な方が使うユーザー補助機能を有効にしていると、この属性に指定した値が読み上げられる仕組みになっています。
この記事では2つの Warning の解消方法を紹介していますので、プロジェクトに合わせてお試しください。
Warning を消す方法
この Warning を消す方法は
- contentDescription 属性を付ける
- Warning を無視する
の2つがあります。
どちらの方法でも良いですが、画像が重要な意味を持っていたり、テキストコンテンツが多いアプリの場合は contentDescription 属性の使用を検討することをお勧めします。
① contentDescription 属性を付ける方法
ImageView の色が変わっている部分にカーソルを合わせると、左側に豆電球のアイコンが表示されるのでクリックします。

Set contentDesciption を選択します。

android:contentDescription=”” が追加されるので、画像の意味を表す適当な文字列を指定します。

今度は contentDescription の部分に Warning がついてしまいました。
カーソルを合わせてみると Hardcoded string “Icon”, should use “@string” resource と表示されます。

これは「文字列を直接書かずに string リソースを使うべきです」という Warning です。string リソースは strings.xml を指しているので、strings.xml に文字列を定義しましょう。
Android Studio 画面左側のプロジェクト構造から app → res → values → strings.xml を開きます。

strings.xml を開いたら文字列を定義します。name 値や文字列はプロジェクトに合わせて変更してください。
<string name="image_desc_icon">Icon</string>
xml ファイルに戻って、以下のように書き換えます。
android:contentDescription="@string/image_desc_icon"
以上で Warning を消すことができます。

② Warning を無視する方法
要素ごとに指定する
ImageView の色が変わっている部分にカーソルを合わせると左側に豆電球のアイコンが表示されるのでクリックします。

Suppress: Add ignore:tools=”contentDesciption” attribute を選択します。

contentDescription を ignore(無視する)コードが追加され、Warning が消えました。

一括指定する
複数の ImageView 要素を使用している場合、全てに tools:ignore=”contentDescription” を書くのが面倒なことがあります。
その場合は、ルート要素に一括指定することもできます。

まとめ
以上が ImageView を使用した時に出る Warning の解消法でした。
Warning はエラーとは違って、プログラムの動作自体に影響が出るわけではありませんが、全て解消しておいた方がコードがスッキリとして気持ちが良いものです。
Warning が出た場合はお試しください。