28

Is there any way to center the inputted text in an EditText field? More specifically, instead of the cursor starting at the left of the box, it should start in the center and move outward towards the left as it is populated with inputs.

Cœur
  • 37,241
  • 25
  • 195
  • 267
capcom
  • 3,257
  • 12
  • 40
  • 50

3 Answers3

57

you should use

 textView.setGravity(Gravity.CENTER_HORIZONTAL);
ColdFire
  • 6,764
  • 6
  • 35
  • 51
  • For future readers, if you want to center both horizontally and vertically, simply use `textView.setGravity(Gravity.CENTER_HORIZONTAL);` – capcom Aug 20 '12 at 19:47
  • I think it makes the vertical centering because the edittext does it automatically if central alignement isn't specified – ColdFire Aug 20 '12 at 19:49
  • Really? Well it seems to center it both vertically and horizontally, so I think it's good. – capcom Aug 20 '12 at 21:00
  • Careful it will cause bug in some devices of Android 5/6 , rf: https://stackoverflow.com/a/26017060/1074998 – 林果皞 Oct 13 '17 at 10:38
22

Try android:gravity="center_horizontal" in the widget definition in your layout file. This will not strictly "move outward towards the left" -- it should move outward in both directions evenly. If you truly mean you want the text to only be on the left side of the EditText, I doubt that will be possible.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
6

Simpler Solution to align text in EditText is to add android:gravity="center" in layout xml. There is no need to add Java code.

Tested Sample Code-

<EditText
                android:id="@+id/FieldName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/back"
                android:inputType="numberDecimal"
                android:gravity="center" />
Ajay B
  • 746
  • 9
  • 19