【问题标题】:TextView width match drawableTop widthTextView 宽度匹配 drawableTop 宽度
【发布时间】:2013-07-12 17:32:31
【问题描述】:

有没有办法让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----] |
|-----------------|

【问题讨论】:

    标签: android textview android-drawable xml-drawable


    【解决方案1】:

    您可以通过将图像和 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>
    

    【讨论】:

    • 它可以工作,但实际上我让两条线左对齐,需要居中。
    • 我知道了,只在TextView中添加android:gravity="center",谢谢。我更喜欢更简单的东西,但看起来不是。