【问题标题】:How to vertically align text in a TextView with Compound Drawable如何使用 Compound Drawable 垂直对齐 TextView 中的文本
【发布时间】:2014-11-05 13:28:47
【问题描述】:

这个问题在某种程度上是my last question的延续。

我现在的问题几乎相同,除了不是在不同视图(即 ImageView 和 TextView)中分离图像和文本之外,我了解到我可以使用属性 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 只是一个分隔符。

... 这是设置上述属性后的布局: (我还没有足够的声望来发布图片,所以这里是link)

(需要说明的是,这只是一个静态示例。我的文本和图像都是在运行时在代码中动态设置的)。

非常感谢任何帮助。

【问题讨论】:

  • 该死!为什么总是要这么简单,我却不明白? @Frank N. Stein,你介意解释一下区别吗?你不想回答这个问题让我接受吗?
  • 刚刚做了。解释很简单。

标签: android android-layout layout textview compound-drawables


【解决方案1】:

将android:layout_gravity="left|center_vertical" 更改为android:gravity="center_vertical"。
layout_gravity 用于将视图定位在容器(布局)内,而gravity 则被引用 View 的内容(在这种情况下,就是 TextView 中的文本)。

【讨论】:

  • 非常感谢!我喜欢 Stack Overflow 社区!
  • 我们在这里互相帮助。也许,有一天,我会提出一个问题,而你会得到答案。
  • @BobMalooga 或其他人,你如何改变图标的​​重力?我预计foregroundGravity 可以工作,但似乎没有。 (例如,如果你需要它们都在顶部以匹配设计)(并且你被 Textview 卡住了,因为它是 NavigationView 的一部分)
  • @nAndroid 要在 TextView 中定位复合 drawable,只需选择正确的 drawable:drawableTop、drawableLeft、drawableBottom 或 drawableRight。您还可以通过选择 drawablePadding 的值来指定填充量。其余的,复合 drawable 是 TextView 的一部分并坚持使用它。
  • @BobMalooga 当您选择左侧时,它会在左侧垂直“居中” - 9 点钟方向。不幸的是,要求是图标浮动到顶部,与顶部的文本对齐,而不是在文本前面居中。我试图使用指向 的可绘制对象,但它似乎不起作用。
猜你喜欢
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2012-07-05
  • 1970-01-01
  • 2014-10-29
相关资源
最近更新 更多