I need to center the Hint text within an EditText
in Android. How do I do this?
This worked for me:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/nombreslayoutinput">
<EditText
android:id="@+id/nombreslayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/nombres"
android:layout_centerInParent="true"
android:gravity="center|center_vertical"
android:ellipsize="start"
android:inputType="textCapWords|textPersonName"
/>
</android.support.design.widget.TextInputLayout>
textAlignment worked for me.
textAlignment="center"
use attribute
android:gravity="center"
I used this code in every circumstances, and it works perfectly without using android:ellipsize="start" to make a hint in center.
<EditText
android:id="@+id/player2Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="robi"
android:inputType="text" />
Unfortunately, neither answer helped me aligning hint, written in LTR language, while the layout orientation was RTL. I needed such layout in a kind of translation application to make overlay icons not interfere with RTL text. But this trick didn't work with hints while there was no any text yet (icons appeared above the hint) and I came to the following java solution to layout problem:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
. . .
if (isRightToLeft()){
EditText guess = (EditText) rootView.findViewById(android.R.id.text1);
CharSequence hint = "\u200F" + guess.getHint();
guess.setHint(hint);
}
. . .
}
The trick was in right-to-left mark to prepend a left-to-right string. And it seems to work, but does anyone know a more elegant solution?
Actually, android:gravity="center_horizontal"
creates the centering effect you're looking for. Similarly, you can use android:gravity="start"
to put hint text at the beginning of the EditText view, and so on.