Android Kotlin |从文本文件中随机抽取一行



很简单,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")
}
}

根据这个答案:

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

更新代码- shuffed ().first()取代random()

由于某种原因每次随机选择同一行。

最新更新