ListView のアイテム選択色と背景色を変更する

ListView の基本的な表示では、全体が真っ黒で選択された項目が真っ赤に表示されたりします。

見やすいのはいいのですが、ちょっとドギツイ配色のため多くの洗練されたアプリケーションでは、デフォルトの色から変更してあったりします。

ここでは ListView の背景色と項目の選択時の色の変更方法をしめします。

ListView の色。何が問題?

ListView は特に色を指定しなければ次のような色合いになります。

非選択状態ではこのようになり・・・

ListView のデフォルト色

項目を選択した時には次のようになります。

ListView のデフォルト色-選択時

まぁ、真っ赤の選択色もいいのですが、時には変えたい場合もあるはずです。ここでは次のようなリストにしてみましょう。

何も選ばなければ白地に黒い文字でリスト表示され・・・

ListView の色を変更

ListView 内の項目選択時は、次のように (ちょっとくすんだ) 緑色とします。

ListView の選択時の色を変更

これをどのように実装するか説明します。

なお、プログラムの全体の構成は ListView の簡単なカスタマイズ - アイコンの追加 で使ったプログラムを利用してます。 まずはそちらを先にご覧になってください。もちろん、色を変えるためだけにアイコンを追加しなければならないことはありませんが、ポイントはカスタムの行毎のレイアウトを利用するというところです。

res/layout/row.xml を次のように変更します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
android:background="@color/list_item"
> <TextView android:id="@+id/row_textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" android:padding="10dip" android:textColor="#000000" /> <ImageView android:src="@drawable/green_arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout>

全体のレイアウトの背景に @color/list_item を指定しています。 これは次のようなリソースをさしています。カラーステートリストリソース (色状態リソース) といい res/color に保存します。 ここでは res/color/list_item.xml として作成しています。

<?xml version="1.0" encoding="utf-8"?>
<selector 
  xmlns:android="http://schemas.android.com/apk/res/android">
<item 
  android:state_selected="false"
  android:state_pressed="false" 
  android:drawable="@color/white" />
<item 
  android:state_pressed="true" 
  android:drawable="@color/green" />
<item 
  android:state_selected="true"
  android:state_pressed="false" 
  android:drawable="@color/green" />
</selector>

これでアイテムの選択時の色を定義しています。

この中の @color 指定は res/values/colors.xml 内の color 要素を指しています。

<resources>
<color name="white">#ffffff</color>
<color name="green">#94cb08</color>
</resources>

以上で ListView の項目の色が変わります。

その他、ListView の背景色も項目に合わせて変更しましたので res/layout/main.xml も載せておきます。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>
<ListView  
  android:id="@+id/listview1"
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:layout_weight="1"
  android:background="@color/white"
/>
</LinearLayout>

以上で ListView の色の変更ができます。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Android 開発入門