在 Android 中保存长文本的最佳实践

Best practice for saving long text in Android

我想知道将字符串值存储在 strings.xml 文件中是否总是最佳做法,即使字符串非常大。更具体地说,我有一个游戏,我在其中显示游戏规则。所有字符的总和大于 700 个字符。目前我将那些长字符串分解成更小的字符串(分成段落)。所以我想知道,拥有那些包含超过 700 个字符的长字符串是否被认为是一种好的做法?我知道必须考虑 HEAP 大小可以处理多少字符,但我怀疑您能否轻松达到极限。根据我正在阅读的内容 Java has the limit set to (2^31 - 1) characters and in Android to somewhere 4-64 million characters.

您可以使用文本文件,而不是在 strings.xml 中保存所有长字符串,并在您想要显示规则文本时读取该文件。

您的布局文件将如下所示:

<ScrollView 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:layout_weight="1.0">
<TextView 
    android:id="@+id/subtitletv"
    android:textSize="18dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
/>

代码将是这样的:

subtitletv = (TextView)findViewById("R.id.helptext");
try {
        FileReader fr=new FileReader(selectedfile);
        BufferedReader br=new BufferedReader(fr);
        String line = null;
        try {
            while((line = br.readLine()) != null)
                 {
                      subtitletv.append(line);
                      subtitletv.append("/n");
                 }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这将易于维护和访问。根据需要进行必要的修改..

我认为在xml中存储字符串没有上限,所以将字符串存储在那里最方便。

如果真的想要不同的机制,你可以选择数据库或者文件。 但是,与从 xml 文件中读取相比,从数据库和文件中读取会花费一些时间,并且需要更多代码才能实现相同的目的。

编辑:

我刚刚注意到你所指的字符串是游戏规则。所以我强烈建议使用 strings.xml,因为 android 使用 XML 将您的应用程序翻译成不同的语言

来自 localization 的官方指南:

Move all strings into strings.xml. As you build your apps, remember not to hard code any string. Instead declare all of your strings as resources in a default strings.xml file which makes it easy to update and localize. Strings in strings.xml file can be extracted, translated and integrated back into your app (with appropriate qualifiers) without any changes to compiled code.