【发布时间】: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() 处。文件中有多少行?