How to set different gravity for TextInputLayout's hint and text entered in edit text. I want to set the hint gravity to start and edit text's text gravity to center. So how can i achieve this. This is my xml code,
<android.support.design.widget.TextInputLayout
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:gravity="start">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/grey"
android:hint="Email"
/>
</android.support.design.widget.TextInputLayout>
In Android, we can set gravity both programmatically and in XML.
To set edit text hint in the center see the code below in which I use android:gravity="center"
in XML.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:backgroundTint="@color/colorAccent"
android:hint="Email" />
For showing the hint at top|left and the text typed in edit text to be at center or to set different gravity for TextInputLayout's hint and text in Android, you need to try the code below.
In .xml you need to set EditText's hint gravity top|left
.
<android.support.design.widget.TextInputLayout
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:hint="Email"
android:backgroundTint="@color/colorAccent" />
</android.support.design.widget.TextInputLayout>
And in your java (activity) file, set EditText's text gravity center programmatically:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etName = (EditText)findViewById(R.id.etName);
etName.setGravity(Gravity.CENTER);
}
See the screenshot with the result:
Different gravity works implementation 'com.google.android.material:material:1.1.0'
and below version but does not work in 1.2.0
or above.
To make it work in 1.1.0
or below follow these steps.
set TextInputEditText
gravity to start in xml
<com.google.android.material.textfield.TextInputEditText id="@+id/text" gravity="start"/>
then programmatically set its gravity to center
text.gravity=Gravity.CENTER
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With