Center a textview vertical to a EditText
What I'm trying to do is have a TextView, and to the right of it an editText that takes up the rest of the space. The textView should be centered vertically along the editText. Now I can do this using an linearlayout, however I would prefer to do it in a relativelayout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/loginText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login:"
android:paddingRight="20dp" />
<EditText开发者_StackOverflow中文版
android:id="@+id/login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/loginText" />
</RelativeLayout>
What you want to do is possible by using the android:layout_alignBottom
and android:layout_alignTop
properties provided by the RelativeLayout
to its children and the android:gravity
property of the TextView
.
These properties allow you to set the bottom/top edge of a view to match the bottom/top edge of another view. By applying them to the TextView
you can effectively make the TextView
match the height of the EditText
control. Then, with the gravity property you can make the text in the TextView
center vertically inside the TextView
control.
The following example should work as you intended:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<TextView android:id="@+id/user_name_label"
android:text="@string/user_name"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_alignBottom="@+id/user_name_text"
android:layout_alignTop="@id/user_name_text"
android:layout_marginRight="5dp"
android:gravity="center_vertical" />
<EditText android:id="@id/user_name_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="@id/user_name_label" />
</RelativeLayout>
add android:layout_gravity="center_vertical"
to your Textview
this would place the textview centered vertically in the parent
精彩评论