Unmotivated

やる気はない

9-Patch のコンテンツ領域は伸縮しない

9-Patch でコンテンツ領域を指定することはよくあるけれど、実は NinePatchDrawable を Background とした View のサイズを変更しても、コンテンツ領域(というか Padding) はうまい感じに伸縮してくれない。

たとえば次のような 9-Patch の画像を用意してコンパイル、NinePatchDrawable として読み込んだ場合を考える。

star

以下のようなレイアウトだった場合を考えてみる。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/star">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/aaa"
            android:background="#ff0000"/>
    </FrameLayout>

    <FrameLayout
        android:layout_width="@dimen/original_drawable_width"
        android:layout_height="@dimen/original_drawable_height"
        android:background="@drawable/star">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/aaa"
            android:background="#ff0000"/>
    </FrameLayout>

    <FrameLayout
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/star">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/aaa"
            android:background="#ff0000"/>
    </FrameLayout>

</LinearLayout>

なんとなく次のように伸縮してくれそうな気がするが…

理想

実際に表示されるレイアウトは以下のようになる。

現実

View.java が setBackgroundDrawable() のときにしか padding を設定してくれないために、このようになってしまう。

コンテンツ領域が伸縮しない場合もあるので当然といえば当然だけれど、今回のような 9-Patch 画像のように、View のサイズについてきてほしい場合もある。

コンテンツ領域を伸縮させる

そこで、 NinePatchDrawable から元々の padding を取得して、現在の View のサイズに合うように伸縮させてみる。

これで以下のように伸縮してくれる。

結果

Comments