AndroidのProgressBarのデザインを変更するときに、ちょっと苦労したお話です。
こんな画像↓
と
こんな画像↓
を組み合わせて、
こんな画像↓
なプログレスバーを表示したいのです。
インターネットの情報
で、インターネットを検索してヒットするのは↓だいたいこんな感じです。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<bitmap android:src="@drawable/background" />
</item>
<item android:id="@android:id/progress">
<clip>
<bitmap android:src="@drawable/progress" />
</clip>
</item>
</layer-list>
layoutファイルで使うときは↓こんな感じですね。
0%、50%、100%のプログレスバーを表示しています。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp"
tools:context=".MainActivity" >
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:progress="0"
android:progressDrawable="@drawable/my_progress" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:progress="50"
android:progressDrawable="@drawable/my_progress" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:progress="100"
android:progressDrawable="@drawable/my_progress" />
</LinearLayout>
で、これを表示してみると、↓こんな感じ。
はい、大変残念な感じです。なんでここまでひどい状態になるのか不思議なくらいです。
- 背景が横に繰り返されてしまっています。リピートの指定なんてしていないのに。
- 進捗を表す前面の水色のバーは両端が歪んでしまっています。
インターネット上で見るサンプルが問題ないように見えるのは、たまたま使用している画像が伸縮したりリピートしたりしても大丈夫な画像だからでしょうか。(それとも自分の実装に抜けがある?)
背景の修正
まずは背景から直していきます。
元々この背景画像を引き伸ばすのは無理があります。
引き伸ばしたら両端も文字も歪んでしまいます。
そういう時は9patchですね。
背景画像を↓このように修正しました。
これだけでは繰り返し表示されるのは変わりません。xmlも修正します。
<item android:id="@android:id/background">
<nine-patch android:src="@drawable/background" />
</item>
<bitmap>
タグを<nine-patch>
タグに変えました。
この時点で以下のような状態になります。
だいぶ理想に近い見た目になってきました。
進捗画像の修正
同じように前面の水色の画像も9patchにします。
画像は↓こんな感じ。
XMLは↓こんな感じです。
<item android:id="@android:id/progress">
<clip>
<nine-patch android:src="@drawable/progress" />
</clip>
</item>
背景のときと修正内容は変わりません。bitmap
タグをnine-patch
タグに変えただけです。
すると↓こうなります。
完成ですヽ(´ー`)ノ
あっさりと修正できてしまいましたが、自分がここまでたどり着くのにAndroidのProgresBarクラスのソースを読んでみたり、xmlを色々と書き換えてみたりといろいろ遠回りしました。
同じように無駄な時間を過ごす人が出ないようにと祈りをこめて記事にしました。
最後にXMLの全文を載せておきます。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<nine-patch android:src="@drawable/background" />
</item>
<item android:id="@android:id/progress">
<clip>
<nine-patch android:src="@drawable/progress" />
</clip>
</item>
</layer-list>