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

标签 java android database sqlite stringbuilder

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

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

数据库的故事如下:

<#c>一只聪明的老猫头鹰

有一只老猫头鹰住在一棵橡树里。

他每天都看到周围发生的事件。

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

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

<#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.

关于java - 如何在使用 java 显示数据库中的数据时将文本水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57919102/

相关文章:

android - 有什么方法可以提高 BitmapFactory.decodeStream() 的速度?

sql - 如何在Postgresql中查询MAX(SUM(relation))?

java - 确定点是否位于椭圆内(包括边缘)

java - 在 JTextPane 中突出显示当前行

java - ListView 不显示在屏幕上

android - 防止多次接收广播

java - 获取触摸释放前后的坐标

javascript - 使用 <img src =""onError =""> 在 MySQL 与 HTTP GET 中存储图像路径

android - 计算多个值出现的次数

java - Jenkins 作业上的 SBT 持续内存不足