TextView宽度与drawableTop宽度匹配

时间:2013-07-12 17:32:31

标签: android textview android-drawable xml-drawable

是否有某种方法使TextView width匹配复合可绘制宽度(XML)?

例如xml代码:

<TextView
    android:id="@+id/textView"
    style="@style/TextIcons"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@drawable/icon_contact"
    android:gravity="center"
    android:lines="2"
    android:text="@string/contact_label" />

我明白了:

|---------------------|
|   |-------------|   |
|   |             |   |
|   |  Drawable   |   |
|   |    View     |   |
|   |             |   |
|   |-------------|   |
|[---Contact Label---]|
|---------------------|

但我真正想要的是:

|-----------------|
| |-------------| |
| |             | |
| |  Drawable   | |
| |    View     | |
| |             | |
| |-------------| |
| [---Contact---] |
| [----Label----] |
|-----------------|

1 个答案:

答案 0 :(得分:4)

您可以通过将图像和TextView分离为相对布局来简单地使其工作。可以很容易地指定对齐某些视图的边缘等等。

以下代码应该做一些接近你想要的事情:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon_contact"
            android:id="@+id/imageView"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp">

    </ImageView>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/contact_label"
            android:id="@+id/textView"
            android:layout_below="@+id/imageView"
            android:layout_alignRight="@+id/imageView"
            android:layout_alignLeft="@+id/imageView"/>
</RelativeLayout>