javaandroidandroid-edittextandroid-gravity

set text gravity center vertical doesn't work in android edit text


I am creating some custom EditText in android (programmatically with java) and when I wanted to setGravity for this EditText to set text gravity at the center vertical, it doesn't work.

enter image description here

Here is my EditText and I used editText.setGravity(Gravity.CENTER_VERTICAL);. But it doesn't set the text to center of the button. Actually editText.setGravity(Gravity.CENTER_HORIZONTAL); works correctly.

I don't want to use editText.setTextAlignment(); because of the version API.

Edited:

Can I set Position of text of EditText manually? With give it my height and with or give some coordinates.


Solution

  • LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER_HORIZONTAL;
    
    editText.setLayoutParams(params);
    

    This is the way you can set gravity programetically

    in XML file

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />
    

    You can use center Gravity.CENTER if you want to apply CENTER_VERTICAL and CENTER_HORIZONTAL both. same will be for the xml file