Android:如何将 TextView 的文本放置在其父 View 的中间

标签 android android-layout textview

我一直在阅读其他问题来寻找答案,但我还没有找到我想要的。 我有一个包含在 LinearLayout 中的 TextView,其属性 android:layout_heightandroid:layout_width 设置为 match_parent

 <LinearLayout
        android:id="@+id/mylayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/mytextview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:singleLine="false"
            android:text="@string/mytext"
            android:textSize="@dimen/mytextsize" />

    </LinearLayout>

我希望 TextView 文本从 LinearLayout 的中间开始;我的意思是,将文本垂直放置在 LinearLayout 的中间,但将 android:layout_height="match_parent" 保留在 TextView 中。

有可能吗?

在 onCreate 方法中的 java 代码中,我用这个来获取父级的中点:

LinearLayout myLinearlayout = (LinearLayout) findViewById(R.id.mylayout);
myLinearLayout.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED);
int linearLayoutHeight = myLinearLayout.getMeasuredHeight();
int middlePoint = linearLayoutHeight / 2;

现在,我不知道如何将文本的顶行定位在该点。谢谢

** 编辑 1 **

我忘了提到 TextView 是可滚动的,而且文本太长。

最佳答案

试试这个

<LinearLayout
android:id="@+id/mylayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:orientation="vertical">
<TextView
    android:id="@+id/mytextview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center|left"
    android:singleLine="false"
    android:text="@string/mytext"
    android:textSize="@dimen/mytextsize"/>

关于Android:如何将 TextView 的文本放置在其父 View 的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274867/

相关文章:

java - 从 Android L 中的 ImageView 获取位图

android - ListView 的自定义滚动发光/边缘颜色?

c++ - GTK+/C++ gtk_label/gtk_textview 文本大小调整

android(在 java 代码中更改字符串)

java - PrintWriter 在 java 中打印 POS 泰米尔字符

java - 尝试使用 FireBase 查看 Activity 中的 "Followers"和 "Following"时出现 NullPointerException

Android ID 作为设备 ID 的替代品

android - 为应用程序android编程提供用户友好的帮助和提示

java - 如何从可选择的 TextView 中获取文本字符串?

android - 无法激活 java 类型 MvxRecyclerView 的 JNI 句柄