在 TextView 的中心设置一些字符串文本

set some text of a string at the center of a TextView

我想在中心修复一些字符串文本。我怎样才能做到这一点? 例如,看看这张照片

我有一个这样的字符串。现在我希望我的字符串的一些单词(标题)水平显示在中心的 TextView 中,但其他单词将像往常一样保留。我该怎么做?

我尝试了以下代码,但它不适用于各种尺寸的设备。

          String string= "                 SYRIA
\n\nSyria oh Syria why do you bleed?
        \nBrother fights brother without thought or need
    \nRuled by a tyrant for so many years
    \nAnd now the split blood is washed away by tears\n"

你可以使用Html.fromHtml。使用这个你只需要一个textview。只要这样做,它应该可以完美地工作

 your_textview.setText(Html.fromHtml("<h><center><b><u>SYRIA</u></b></center></h>\n" +
            "    <p>Syria oh Syria why do you bleed?</p> </br>\n" +
            "    <p>Brother fights brother without thought or need</p> </br>\n" +
            "    <p>Ruled by a tyrant for so many years</p> </br>\n" +
            "    <p>And now the split blood is washed away by tears</p> </br>"));

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">


    <TextView
        android:id="@+id/textView1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:text="seria"
        android:textSize="20sp"
        />


    <TextView
        android:id="@+id/textView2"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:text="Syria oh Syria why do you bleed?
        \nBrother fights brother without thought or need
    \nRuled by a tyrant for so many years
    \nAnd now the spilt blood is washed away by tears"
        />

</LinearLayout>

您可以使用 2 个不同的 Textview,或者如果只有一个 textview,您可以使用 HTML 或 Spannable String。 Spannable可以这样使用:

TextView resultView = new TextView(this);
final String SyriaText = "Syria";
final String OtherText = "Other Text";
final String result = SyriaText + "  " + OtherText;
final SpannableString finalResult = new SpannableString(result);
finalResult.setSpan((new AlignmentSpan.Standard(Alignment.ALIGN_CENTER), 0, SyriaText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
resultView.setText(finalResult);

您也可以使用 Spannable 对其进行样式设置。您可以从以下位置了解更多信息:https://developer.android.com/reference/android/text/Spannable.html