android - 在垂直方向的 LinearLayout 中将 TextView 和 EditText 左对齐

标签 android xml android-edittext android-linearlayout

我使用 LinearLayout 作为 View 组,它包含两个 subview (TextViewEditText)。我的 XML 代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text View"
        android:textSize="20sp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Edit Text"
        android:textSize="20sp" />

</LinearLayout>

这将产生以下设计:

enter image description here

如左侧放大 View 所示,TextViewEditText 不是垂直对齐的(EditText 缩进了一点更多如红色小箭头所示)。

似乎在提示和下方的线周围有一些填充(一些 dp),以防止它们“接触”其视野的左边缘。有什么方法可以强制 EditText 中的提示挤到其视野的左侧吗?

我怎样才能摆脱这种缩进,除了添加填充和边距

感谢您的任何想法和建议!

最佳答案

在不添加任何填充和边距的情况下,您可以为 Edittext 的背景使用自定义可绘制对象以删除默认填充

在 drawable/edittext_bg.xml 中

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item
        android:top="-2dp"
        android:right="-2dp"
        android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="#000000" />
        </shape>
    </item>
</layer-list>

现在在你的编辑文本中使用它:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/edittext_bg"
        android:hint="Edit Text"
        android:textSize="20sp" />

输出:

enter image description here

关于android - 在垂直方向的 LinearLayout 中将 TextView 和 EditText 左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42838577/

相关文章:

android - Android:Gradle导入无法解决

android - 在键盘上显示 "Done"

android - 如何将多个字体添加到单个 EditText 意味着每个单词根据运行时间有不同的字体

android - 如何在 react 导航标签栏内添加图像?

android - 如何获取通知ID?

android - 布局检查器未显示可组合树

html - 使用XPath,如何在没有前面的文本的情况下获得完全匹配的标记?

python - 使用lxml etree在Python中将大型xml文件聚合到字典需要太长时间

Android RecyclerView Edittext 问题

android - editText 小部件的正则表达式,这是必要的吗?