【问题标题】:Android Kotlin | Picking random line from text file安卓科特林 |从文本文件中选择随机行
【发布时间】:2022-11-30 02:03:45
【问题描述】:

很简单,android kotlin。 我在项目资产文件夹中有一个文件,每行都有一个句子。 我想要的是,当我打开对话框时,它会选择随机行并将其作为对话框消息。 我找不到任何合适的解决方案。 对话框的代码:

class JokeFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val sentence: String = //random line from the file
            // Use the Builder class for convenient dialog construction
            val builder = Builder(it)
            builder.setMessage(sentence)
                .setNegativeButton(R.string.cancel){ _, _->}
            // Create the AlertDialog object and return it
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
}

【问题讨论】:

  • 有什么理由不能用字符串行创建字符串数组资源吗?然后你可以从数组中拉出一个随机字符串。如果你把它放在一个文本文件中,你将不得不做文件 IO,这将涉及必须首先在后台线程中加载文件,然后在加载文件后在主线程上更新对话框。字符串资源在应用程序启动时预加载,因此您不必担心使用后台线程来检索它们。
  • 我没有看到文件。我没看到你打开文件。我没看到你在读文件。你做的还不够。
  • 当然,我知道如何读取整个文件,但在第 5 行我寻求帮助
  • which would involve having to do load the file in a background thread first? @Tenfour04。根本不需要。也许如果文件有兆字节大小。进一步在字符串数组中键入所有数据是一项糟糕的工作。没有一个文件是完美和灵活的。
  • 第 5 行第五次停在 .readLine() 处。文件中有多少行?

标签: android kotlin file


【解决方案1】:

基于this的回答:

fun readRandomLineFromAsset(context: Context, fileName: String): String =
        context
            .assets
            .open(fileName)
            .bufferedReader()
            .use(BufferedReader::readText)
            .lines()
            .random()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多