如何在使用 java 显示数据库中的数据时将文本水平居中

How to center text horizontally in a line while showing data from database with java

我在数据库中有一些故事。每一行都有故事。我想用 java 显示数据库中的故事。我可以显示数据库中的故事。

我的问题是我想显示一些水平居中的线条。为此,我在该行的文本之前添加了 <#c> 标记,以使文本水平居中。

数据库故事如下:

<#c>一个聪明的老人Owl

有一位老人 owl 住在一棵橡树里。

他每天都看到身边发生的事情。

昨天他看到一个男孩帮一个老人提着一个沉重的篮子。

今天他看到一个女孩对她妈妈大喊大叫。

<#c>越看越少说

<#c>越说越少,听到的越多。

他听到人们在说话和讲故事。

.....

故事的寓意:

<#c>你要善于观察,少说多听。

<#c>这会让你成为一个有智慧的人。

我在下面这样试过。

SQLiteDatabase sqLiteDatabase = DatabaseHelper.getInstance(context).getWritableDatabase();
Cursor cursor2 = sqLiteDatabase.rawQuery("SELECT subject FROM work", new String[]{});
if (cursor2.getCount() == 0) {
        Toast.makeText(context, "No Data to show", Toast.LENGTH_LONG).show();

    } else {
        while (cursor2.moveToNext()) {
            listItem2.add(cursor2.getString(cursor2.getColumnIndex("subject")));
        }

        cursor2.close();
    }

以上代码显示了包括<#c>在内的所有文本。但我想删除 <#c> 并使 <#c> 标记的线水平居中。

我尝试使用 StringBuilder 和 append 函数。但是我无法申请。

StringBuilder sb = new StringBuilder();

我不明白我将如何实现它。

我非常需要你的帮助。

如果你只是想

  1. 删除行首的"<#c>"标签,如果有
  2. 如果行中有这样的标签,则将文本居中放置在列表项中

那么您可以尝试这样做在您设置列表项文本内容的代码部分:

// get the TextView instance first
TextView textView = ((TextView) rootView.findViewById(R.id.text2));
// then get the text in order to check if it begins with the tag
String text = args.getString(ARG_OBJECT2);
// find out if it begings with the tag
boolean beginsWithTag = text.startsWith("<#c>");

// then handle the case of a leading tag
if (beginsWithTag) {
    // replace the tag with an empty String and trim it
    text = text.replace("<#c>", "").trim(); // removes the leading tag 
    text.trim(); // removes all trailing or leading whitespaces
    textView.setGravity(Gravity.CENTER);
}

// finally just add the text
textView.setText();

Please note that I don't have your entire code and cannot test this in any suitable way. You will have to debug any errors yourself. You can also shorten this code, but I think having a few lines more than necessary shows the way to do it more clearly in this case.