首页 > 解决方案 > 在具有特定设计的 EditText 中放置标签

问题描述

我需要为 Android 重写一个 iOS 应用程序。布局应该看起来相似,我在这个问题上苦苦挣扎:

我想在 EditText 的左侧有一个标签。它应该粘在那里并且不要让 EditText 文本覆盖标签:

EditText 的标签

我尝试过在 Android Studio 中使用界面生成器,如下所示: 在此处输入图像描述

问题是,EditText 的文本没有隐藏在标签后面。有任何想法吗?

编辑: 由于我的问题不清楚:

我想要一个 EditText 内的标签。它应该贴在左边并且与 EditText 的输入有一个边距。

标签: androidandroid-edittexttextview

解决方案


尝试在您的 xml 中使用以下代码并检查,这将使您的标签文本与用户可以输入密码的密码字段对齐。

<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:layout_margin="@dimen/padding_medium">

        <TextView
                android:id="@+id/label"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:text="Password"
                android:layout_marginTop="@dimen/padding_medium"
                android:gravity="center_vertical"
                android:paddingLeft="@dimen/padding_xsmall"
                android:textSize="22sp"
                android:textColor="@android:color/holo_red_dark"
                app:layout_constraintHeight_default="wrap"
                android:paddingStart="@dimen/padding_xsmall"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintWidth_default="wrap"/>

            <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="0dp"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toRightOf="@id/label"
                    app:layout_constraintRight_toRightOf="parent"
                    android:layout_marginStart="4dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="4dp"
                    android:background="@null"
                    android:padding="4dp"
                    android:imeOptions="actionNext"
                    android:lines="1"
                    android:inputType="textPassword"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

注意:我使用了 androidx 控件,因为我正在使用新的材料设计库。如果您使用支持库,则需要用支持库中的控件替换它们。


推荐阅读