Search code examples
androidtextviewandroid-edittextlinecenter

How to make the text center vertical in a line in TextView of Android


I have a multi-line edit text with a 100dp lineSpacingExtra.

Now the text is shown at the top of a line. And the cursor's height is same as line height , it's much taller than the text's height.

How can I make the text shown in the center of the line? Or if I can adjust the padding top or padding bottom of the text in a line.

Note: What I mean is NOT using android:gravity="center_vertical" to make the text center vertical in the TextView. I want to show the text center vertically in the line.

The xml is as below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:fadingEdge="vertical"
        android:gravity="top"
        android:inputType="textCapSentences|textMultiLine|textShortMessage"
        android:lineSpacingExtra="100dp"
        android:longClickable="false"
        android:minLines="10"
        android:paddingBottom="5dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="5dp"
        android:scrollbars="vertical"
        android:text="Text ABCDE\n Line2"
        android:textAlignment="center"
        android:textSize="16sp" />
</LinearLayout>

Any help is appreciated. THX!


Solution

  • Attach my result here:
    There's no way to do this in an application.
    Because the TextView draws the text at the top of a line in framework.
    If u want the visual effect that the text shown center vertically in a line, the framework code must be modified.

    The file location is:
    frameworks/base/core/java/android/text/StaticLayout.java

    The change:

    -        lines[off + DESCENT] = below + extra;
    +        lines[off + DESCENT] = below + extra/2;//Show the text center vertically in the line.
    

    Please correct me if something is wrong or there's a better way to do this.