Search code examples
javaandroidandroid-layoutandroid-edittextandroid-xml

Android - Center text inside EditText programmatically


I'm writing a custom Android view which contains an EditText. I want to be able to center the text vertically through Java code but it's not working.

My failure

As you can see from the image above, the text is not centering vertically. I set the EditText background to a light red so you can see the layout bounds of it. I have an EditText on the left of it rendered through XML code and it it working correctly.

How do I get the text to show correctly?

.

Here is my code for the middle EditText:

txtSearch = new EditText(context);
txtSearch.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1f));
txtSearch.setGravity(Gravity.CENTER_VERTICAL);
txtSearch.setBackgroundColor(context.getResources().getColor(R.color.nowl_red_transparent_12));//Color.TRANSPARENT);
txtSearch.setHint("Search");
txtSearch.setHintTextColor(context.getResources().getColor(R.color.text_hint));
txtSearch.setInputType(InputType.TYPE_CLASS_TEXT);
txtSearch.setMaxLines(1);
txtSearch.setHorizontalScrollBarEnabled(true);
txtSearch.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
txtSearch.setTextSize(16f);
txtSearch.setEllipsize(TextUtils.TruncateAt.END);
txtSearch.setText("Y u no center");
container.addView(txtSearch);

and here is the code for the EditText on the left which renders correctly:

<EditText
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:background="@color/transparent"
    android:hint="test" />

I tried practically everything. I used setGravity(Gravity.CENTER_VERTICAL), removed/added properties, and more. Nothing of which worked. Is this a bug with Android or is there something I'm missing here? It looks like this in the UI Preview and in actual Android devices as well.


Solution

  • From the looks of it, it does look aligned to some degree. If it was top aligned, it would be on the far top with maybe 1dp of margin. If it was bottom aligned, it would be so high either.

    I drew a green box on top of your original image to show what I think is what it is aligned relative to.

    Padding box

    Given you have replaced the original background with a custom color, It might be possible that Android is pulling some unexpected default settings either from your context object or the system defaults and adds a padding (although I don't remember Android having any padding by default). Have you tried txtSearch.setPadding(0, 0, 0, 0) just in case?