24

I am making a small app for a tablet, something like a display sign.

I have a few text elements that are center aligned in the display sign. When I tap on it, it gets converted to editText. I want the edit text in such a way that the text in it is center aligned and content wrapped. But when i input something, editText expands both ways, keeping the text aligned to the center. I want to do the same thing with right aligned text elements (only difference is that the edit text would expand only towards the left).

When i am trying to do this right now it expands towards the left.This is my code for laying out the edit Text element

tempView=new EditText(this);
((EditText) tempView).setTextSize(shrinkedFontSize);
((EditText) tempView).setTypeface(tf);
((EditText) tempView).setText(tempInput.getText());     
((EditText) tempView).setGravity(Gravity.CENTER);
layout.addView(tempView, tempParams);

I am setting the width of the layout as Wrap_content in the layout parameters. I have also specified the x and y in my layout parameters for the top left corner of the edit text.

Is there any way to achieve this ?

Dhaval Patel
  • 263
  • 1
  • 3
  • 5
  • textView.setGravity(Gravity.CENTER_HORIZONTAL); https://stackoverflow.com/questions/12043809/android-center-text-inside-edittext-programmatically – DC Design Jun 13 '21 at 09:00

2 Answers2

48

This should resolve your problem:

EditText t = (EditText) findViewById(R.id.text);
t.setGravity(Gravity.CENTER);

... in XML:

<EditText
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="text" />

It makes the EditText inputField entered text centered horizontally.

You can change the layout_width from fill_parent to 150 dp or any other size, but not wrap_content. The text will be centered horizontally.

Set the t.setGravity(Gravity.RIGHT); or LEFT, that makes entered text left or right alignment.

Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Asad Rao
  • 3,190
  • 1
  • 22
  • 26
18

This is a tested simpler solution. Just add android:gravity="center" to the layout XML file to align the text to center of EditText. There is no need to change Java code.

<EditText
    android:id="@+id/LastName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/back"
    android:inputType="numberDecimal"
    android:gravity="center" />
Pang
  • 9,564
  • 146
  • 81
  • 122
Ajay B
  • 746
  • 9
  • 19
  • both answers are correct. however, the op were trying to do it in java so the other answer is more accurate imo – SDIDSA Mar 28 '19 at 20:02