如何在带有组合图标的TextView中垂直对齐文本

15

这个问题在某种程度上是我上一个问题的延续。

我的问题现在基本相同,只不过我学到了一种方法,可以使用属性android:drawableLeft为文本设置图像(Eclipse通过LinearLayout行上的警告图标向我提出了建议)。

我认为唯一的区别是,我将不再使用setImageResource()方法来设置ImageView,而是使用setCompoundDrawablesWithIntrinsicBounds()方法来设置TextView的drawableLeft属性。但实际上,当我做出改变时,我重新遇到了最初的问题:文本与视图顶边对齐而不是居中对齐。

这是我的TextView的外观:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >       
    <TextView 
        android:id="@+id/account_login"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/pm_gmail"
        android:drawablePadding="8dp"
        android:text="example@gmail.com"
        android:paddingLeft="16dp"
        android:layout_gravity="left|center_vertical" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:layout_centerVertical="true"
        android:layout_below="@id/account_login"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="5dp"
        android:background="#DDDDDD" />

</RelativeLayout>

第二个View只是一个分隔符。

... 设置了上述属性后,布局如下所示: (我还没有足够的声望来发布图片,所以这里是链接

(只是为了明确起见,这只是一个静态示例。我的文本和图像均在运行时动态设置代码)。

非常感谢任何帮助。


糟糕!为什么总是这么简单,但我就是不明白呢?@Frank N. Stein,你介意给我解释一下区别吗?你不想回答问题让我接受它吗? - Nick Fanelli
刚刚完成了。解释非常简单。 - Phantômaxx
1个回答

27
android:layout_gravity="left|center_vertical" 更改为 android:gravity="center_vertical"
layout_gravity 用于定位容器(布局)中的视图,而 gravity 则是针对视图内容的(也就是在此 TextView 中的文本)。

1
非常感谢!我喜欢 Stack Overflow 社区! - Nick Fanelli
10
我们在这里相互帮助。也许有一天,我会有问题,而你会有答案。 - Phantômaxx
@BobMalooga或其他人,你怎样改变图标的重力?我原以为foregroundGravity可以起作用,但似乎并没有。比如说,如果你需要将它们都置于顶部以符合设计要求(而且你只能使用带有复合可绘制对象的TextView,因为它是NavigationView的一部分)。 - nAndroid
@nAndroid:为了将复合绘图放置在TextView内部,只需选择正确的drawable:drawableTop、drawableLeft、drawableBottom或drawableRight。您还可以通过选择drawablePadding的值来指定填充量。对于其余部分,复合绘图是TextView的一部分,并与之保持一致。 - Phantômaxx
1
@BobMalooga 当您选择左侧时,它会在左侧垂直“居中”-9点钟方向。不幸的是,要求图标浮动到顶部,与其顶部的文本对齐,而不是在文本前面居中。我尝试使用指向<bitmap gravity="something" src=realdrawable.png/>的可绘制对象,但似乎没有起作用。 - nAndroid
我不确定我理解您的要求。如果我理解正确,您想要图标在文本顶部,文本在底部。如果是这样,请选择 darawableTop - Phantômaxx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接